我想要解析像这样的JSON格式:
{
"key_1" : {
"key_2" : "value"
}
}
Run Code Online (Sandbox Code Playgroud)
然后分配"value"给变量.
这是我的代码:
var variableShouldBeAssigned: String
if let x = (jsonResult["key_1"]? as? NSDictionary) {
if let y = (x["key_2"]? as? String) {
variableShouldBeAssigned = y
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试向下转换x["key_2"]?为String 时会发生错误,但从向下转换jsonResult["key_1"]?为NSDictionary是可以的.
我可以通过使用x["key_2"]替换来解决错误x["key_2"]?,但我真的不知道为什么它只适用于jsonResult["key_1"]?.
谁能告诉我原因?