Ecco una soluzione pronto per la produzione in Swift 3:
extension String {
init(unicodeScalar: UnicodeScalar) {
self.init(Character(unicodeScalar))
}
init?(unicodeCodepoint: Int) {
if let unicodeScalar = UnicodeScalar(unicodeCodepoint) {
self.init(unicodeScalar: unicodeScalar)
} else {
return nil
}
}
static func +(lhs: String, rhs: Int) -> String {
return lhs + String(unicodeCodepoint: rhs)!
}
static func +=(lhs: inout String, rhs: Int) {
lhs = lhs + rhs
}
}
Usage:
let a = String(unicodeCodepoint: 42) // "*"
var b = a + 126 // "*~"
b += 33 // "*~!"
Si noti che questo funziona con tutti ASCII e codepoints Unicode, in modo da può fare questo:
var emoji = String(unicodeCodepoint: 0x1F469)! // ""
emoji += 0x200D // ""
emoji += 0x1F4BB // ""
Come nota personale, non lo userei nel mio codice. Mi sarei aspettato che ":" + 40
diventasse ":40"
, non ":("
. Se preferisci la seconda dove 40
diventa "("
, allora questo dovrebbe funzionare bene per te :)
fonte
2017-04-07 21:43:04
Potrebbe anche usare 's + =" \ (UnicodeScalar (x)) "' – dasblinkenlight
Questo è un buon punto. E per pulirlo, è possibile aggiungere l'operatore + = 'func + = (inout left: String, right: Int) {left + =" \ (UnicodeScalar (right)) " }' – connor
c'è un modo per ottenere valore decimale dal carattere in rapido –