在Swift中将Unicode转换为UTF8 [英] Unicode to UTF8 in Swift

查看:698
本文介绍了在Swift中将Unicode转换为UTF8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Maps API,并且在国外搜索某些地址时,该地址返回时嵌入了Unicode字符,如下所示:

I am using the Maps API and when searching for some addresses in foreign countries, the address comes back with Unicode characters embedded like this:

"Place du Panth\U00e9on",
"75005 Paris"

此例中的unicode字符为\ U00e9,即é

The unicode character in this instance is \U00e9 which is é

我遇到的麻烦是,如果我将这些数据保存在JSON文件中并尝试将其读回,SwiftyJSON就会呕吐. SwiftyJSON不喜欢反斜杠字符'\'.JSON是有效的,即使我可以读取它,也仍然不能令人满意,因为我宁愿é以及所有其他Unicode字符都能正确显示.

The trouble I have having is that SwiftyJSON pukes if I have saved this data in a JSON file and try to read it back. SwiftyJSON does not like the back slash character '\' The JSON is valid and even if I could read it, it is still not good as I would rather have é displayed properly as well as all other Unicode characters.

有人对在Swift中将所有Unicode字符转换为该字符的UTF8编码有任何想法吗?

Does anyone have any ideas on how to convert all unicode characters to UTF8 encoding of that character in Swift?

我应该编写一个搜索所有Unicode字符然后将其转换的函数吗?

Should I just write a function that searches for all of the Unicode characters and then convert them?

推荐答案

除非有人有更好的主意,否则我只是编写了此函数,该函数现在对我有用.

Unless someone has a better idea, I just wrote this function that is doing the trick for me now.

func convertFromUnicode(var myString:String) -> String {
    let convertDict:[String:String] = ["\\U00c0":"À", "\\U00c1" :"Á","\\U00c2":"Â","\\U00c3":"Ã","\\U00c4":"Ä","\\U00c5":"Å","\\U00c6":"Æ","\\U00c7":"Ç","\\U00c8":"È","\\U00c9":"É","\\U00ca":"Ê","\\U00cb":"Ë","\\U00cc":"Ì","\\U00cd":"Í","\\U00ce":"Î","\\U00cf":"Ï","\\U00d1":"Ñ","\\U00d2":"Ò","\\U00d3":"Ó","\\U00d4":"Ô","\\U00d5":"Õ","\\U00d6":"Ö","\\U00d8":"Ø","\\U00d9":"Ù","\\U00da":"Ú","\\U00db":"Û","\\U00dc":"Ü","\\U00dd":"Ý","\\U00df":"ß","\\U00e0":"à","\\U00e1":"á","\\U00e2":"â","\\U00e3":"ã","\\U00e4":"ä","\\U00e5":"å","\\U00e6":"æ","\\U00e7":"ç","\\U00e8":"è","\\U00e9":"é","\\U00ea":"ê","\\U00eb":"ë","\\U00ec":"ì","\\U00ed":"í","\\U00ee":"î","\\U00ef":"ï","\\U00f0":"ð","\\U00f1":"ñ","\\U00f2":"ò","\\U00f3":"ó","\\U00f4":"ô","\\U00f5":"õ","\\U00f6":"ö","\\U00f8":"ø","\\U00f9":"ù","\\U00fa":"ú","\\U00fb":"û","\\U00fc":"ü","\\U00fd":"ý","\\U00ff":"ÿ"]

    for (key,value) in convertDict {
        myString = myString.stringByReplacingOccurrencesOfString(key, withString: value)

    }
 return myString
}

这篇关于在Swift中将Unicode转换为UTF8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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