美文网首页
Swift5 - emoji表情与UInt64数字或字符串转换

Swift5 - emoji表情与UInt64数字或字符串转换

作者: minse | 来源:发表于2022-11-27 13:31 被阅读0次

    最近做项目的时候需要处理emoji表情,网上搜索的代码版本是是比较早期的版本,并不能直接在Swift5的环境下使用,由于iOS13以后苹果官方弃用了UInt32类型的转换,参考了网上的代码案例自己琢磨写了一个可行的转换方法。

    代码如下:

    /// test emoji(with: "0x1f603") -> "😃"
    func emoji(with code: String) -> String {
        let scanner = Scanner(string: code)
        var result: UInt64 = 0
        scanner.scanHexInt64(&result)
        // 强转类型有风险,所以用取巧的方式将UInt64转为Int类型,由于取值是负,将使用绝对值
        // 如果是使用 0x123456 之类的十六进制数字类型,可直接进入下面的步骤
        let res = abs(result.distance(to: 0))
        if let unicode = Unicode.Scalar(res) {
            let character = Character(unicode)
            // 也可以使用String(character)
            return "\(character)"
        }
        return code
    }
    

    相关文章

      网友评论

          本文标题:Swift5 - emoji表情与UInt64数字或字符串转换

          本文链接:https://www.haomeiwen.com/subject/otahfdtx.html