Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将字典的字符串表示形式转换为Swift中的字典?_Swift_String_Swift4 - Fatal编程技术网

将字典的字符串表示形式转换为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