Guard not unwrapping optional

不羁的心 提交于 2019-12-08 17:07:51

问题


I'm trying to process a JSON object, using a guard statement to unwrap it and cast to the type I want, but the value is still being saved as an optional.

guard let json = try? JSONSerialization.jsonObject(with: data) as? [String:Any] else {
    break
}

let result = json["Result"]
// Error: Value of optional type '[String:Any]?' not unwrapped

Am I missing something here?


回答1:


try? JSONSerialization.jsonObject(with: data) as? [String:Any]

is interpreted as

try? (JSONSerialization.jsonObject(with: data) as? [String:Any])

which makes it a "double optional" of type [String:Any]??. The optional binding removes only one level, so that json has the type [String:Any]?

The problem is solved by setting parentheses:

guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String:Any] else {
    break
}

And just for fun: Another (less obvious?, obfuscating?) solution is to use pattern matching with a double optional pattern:

guard case let json?? = try? JSONSerialization.jsonObject(with: data) as? [String:Any] else {
    break
}


来源:https://stackoverflow.com/questions/43123036/guard-not-unwrapping-optional

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!