将字典的字符串表示形式转换为Swift中的字典?
如果我将以下内容作为将字典的字符串表示形式转换为Swift中的字典?,swift,string,swift4,Swift,String,Swift4,如果我将以下内容作为字符串,如何将其转换为Swift 4中的词典 {“cover\u image”:“CI”,“profile\u image”:“PI”,“github”:“location”:“北极和南极之间的某处”,“name”:“R”,“website”:“mysitesucksyoudon'twannavisititrightnow.imforreal”,“about”:“是的,我是人。”}您可以使用jsonserialization方法类函数jsonObject(使用data:dat
字符串
,如何将其转换为Swift 4中的词典
{“cover\u image”:“CI”,“profile\u image”:“PI”,“github”:“location”:“北极和南极之间的某处”,“name”:“R”,“website”:“mysitesucksyoudon'twannavisititrightnow.imforreal”,“about”:“是的,我是人。”}
您可以使用jsonserialization
方法类函数jsonObject(使用data:data,options opt:JSONSerialization.ReadingOptions=[])抛出->任意
:
let str = """
{"cover_image":"CI","profile_image":"PI","github":"","location":"Somewhere between the north pole and the south pole","name":"R","website":"mysitesucksyoudon'twannavisititrightnow.imforreal","about":"Yeah, I'm a human."}
"""
let dict = (try? JSONSerialization.jsonObject(with: Data(str.utf8))) as? [String:String] ?? [:]
print(dict) // ["name": "R", "location": "Somewhere between the north pole and the south pole", "website": "mysitesucksyoudon\'twannavisititrightnow.imforreal", "github": "", "cover_image": "CI", "about": "Yeah, I\'m a human.", "profile_image": "PI"]
我建议改用Codable