如何在SWIFT 5中解码像&xc3xa6"这样的UTF8文字? [英] How do you decode utf8-literals like "xc3xa6" in Swift 5?

查看:59
本文介绍了如何在SWIFT 5中解码像&xc3xa6"这样的UTF8文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从蓝牙特征获取WiFi SSID的列表。每个SSID都表示为一个字符串,有些SSID具有这些UTF8字面值,如";xc3xa6";。

我尝试了多种方式进行解码

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

我希望如此

print(dec)
> æ

等,但它不起作用,它只会导致

print(dec)
> xc3xa6

如何在SWIFT 5中解码字符串中的UTF-8文字?

推荐答案

您只需解析字符串,将每个十六进制字符串转换为UInt8,然后使用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!")
}

这篇关于如何在SWIFT 5中解码像&xc3xa6"这样的UTF8文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆