护罩不展开可选 [英] Guard not unwrapping optional

查看:96
本文介绍了护罩不展开可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用guard语句处理JSON对象以将其解包并转换为所需的类型,但是该值仍保存为可选值.

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

我在这里想念东西吗?

推荐答案

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

被解释为

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

使其成为类型[String:Any]??的双重可选". 可选绑定仅删除一个级别,因此json具有 类型[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
}

这篇关于护罩不展开可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆