Home > other >  How do you decode utf8-literals like "\xc3\xa6" in Swift 5?
How do you decode utf8-literals like "\xc3\xa6" in Swift 5?

Time:11-20

I am fetching a list of WiFi SSID's from a Bluetooth characteristic. Each SSID is represented as a string, some have these UTF8-Literals like "\xc3\xa6".

I have tried multiple ways to decode this like

let s = "\\xc3\\xa6"
let dec = s.utf8

From this I expect

print(dec)
> æ

etc. but it doesn't work, it just results in

print(dec)
> \xc3\xa6

How do I decode UTF-8 literals in Strings in Swift 5?

CodePudding user response:

You'll just have to parse the string, convert each hex string to a UInt8, and then decode that with String.init(byte:encoding:):

let s = "\\xc3\\xa6"
let bytes = s
    .components(separatedBy: "\\x")
    // components(separatedBy:) would produce an empty string as the first element
    // because the string starts with "\x". We drop this
    .dropFirst() 
    .compactMap { UInt8($0, radix: 16) }
if let decoded = String(bytes: bytes, encoding: .utf8) {
    print(decoded)
} else {
    print("The UTF8 sequence was invalid!")
}
  • Related