swift – 警卫不打开可选

前端之家收集整理的这篇文章主要介绍了swift – 警卫不打开可选前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试处理一个 JSON对象,使用一个guard语句来展开它并转换为我想要的类型,但该值仍然被保存为可选项.
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

我在这里错过了什么吗?

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

被解释为

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

这使它成为[String:Any]类型的“双重可选”.
可选绑定只删除一个级别,以便json具有
类型[String:Any]?

通过设置括号来解决问题:

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

只是为了好玩:另一个(不太明显?,混淆?)解决方案是
使用模式匹配双重可选模式:

guard case let json?? = try? JSONSerialization.jsonObject(with: data) as? [String:Any] else {
    break
}
原文链接:https://www.f2er.com/swift/319235.html

猜你在找的Swift相关文章