加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 强制展开的目的

发布时间:2020-12-14 02:29:31 所属栏目:百科 来源:网络整理
导读:在 swift文档中,您可以找到: if convertedNumber != nil { println("convertedNumber has an integer value of (convertedNumber!).")}// prints "convertedNumber has an integer value of 123." 有了这个解释 Once you’re sure that the optional does
在 swift文档中,您可以找到:
if convertedNumber != nil {
    println("convertedNumber has an integer value of (convertedNumber!).")
}
// prints "convertedNumber has an integer value of 123."

有了这个解释

Once you’re sure that the optional does contain a value,you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says,“I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value:

好的,明白了,但它的用处是什么?如果我没有强行拆包,那就不一样了:

if convertedNumber != nil {
    println("convertedNumber has an integer value of (convertedNumber).")
}
// prints "convertedNumber has an integer value of 123."

感谢启发我:)

Wouldn’t be the same if I didn’t forced the unwrapping

不可以.可选是另一种类型.如果您实际上在没有展开的情况下运行上面的代码(在操场上这是微不足道的),您可以立即看到差异.

可选打印为可选(123),打开打印为123.您无法将可选项传递给需要特定类型的内容而无需先将其打开.

理解Optionals是完全不同的类型,而不是特定类型的特殊类型(例如,没有“可选的Int”,有一个包含Int的Optional)是理解这一点的关键.如果你对更长的解释感兴趣,我已经写了here.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读