Swift Encode/decode emojis

Your encoding code can be simplified to

func encode(_ s: String) -> String {
    let data = s.data(using: .nonLossyASCII, allowLossyConversion: true)!
    return String(data: data, encoding: .utf8)!
}

Note that it encodes all non-ASCII characters not only
Emojis (as \uNNNN where NNNN is the hexadecimal code of the Unicode character, or as \NNN where NNN is an octal code). Decoding is done by reversing the transformations:

func decode(_ s: String) -> String? {
    let data = s.data(using: .utf8)!
    return String(data: data, encoding: .nonLossyASCII)
}

This returns an optional because it can fail for invalid input.

Example:

let s = "Hello πŸ˜ƒ."
let e = encode(s)
print(e) // Hello \ud83d\ude03.

if let d = decode(e) {
    print(d) // Hello πŸ˜ƒ.
}

Of course you can also define the code as extension methods of the
String type, and you might want to choose better function names.

Leave a Comment