简体   繁体   English

Swift中类型和显式展开类型之间的区别

[英]Difference between a type and an explicitly unwrapped type in Swift

This one is really puzzling me: What's the difference between an implicitly unwrapped optional, and the type itself? 这个让我很困惑:一个隐式解包的可选项与类型本身有什么区别?

For example, 例如,

var s:String!
var s2: String

Aren't these two exactly the same? 这两个不完全一样吗? They represent a String that can't be nil, so why on Earth do we need the ! 它们代表的是一个不能为零的字符串,所以为什么在地球上我们需要它! thing? 事情?

The implicitly unwrapped optional is an optional , in fact you can assign a nil value 隐式展开的可选项是可选的 ,实际上您可以指定一个nil

var s: String! = nil

But declaring as implicitly unwrapped, you don't have to append ? 但声明为隐式解包,你不必追加? every time you use it, so, as its name states, it is implicitly unwrapped because it is supposed to contain a non nil value. 每次使用它时,因此,正如其名称所示,它被隐式解包,因为它应该包含非零值。

Consequence: if an implicitly unwrapped is nil, most likely when you use it in your code a runtime exception will be generated - for instance: 结果:如果隐式展开为零,很可能在您的代码中使用它时,将生成运行时异常 - 例如:

let s: String! = nil
var s1: String = s // Execution was interrupted, reason: EXC_BAD_INSTRUCTION ...

The question could turn into: why do implicitly unwrapped optionals exist? 问题可能变成:为什么存在隐式解包的期权? The answer is that they are needed to Resolving Strong Reference Cycles Between Class Instances , and a few other cases. 答案是它们需要解决类实例之间的强引用循环以及其他一些情况。

I would personally avoid declaring implicitly unwrapped variables in my code, unless I have a very good reason (such as to solve reference cycles, as mentioned above) 我个人会避免在我的代码中声明隐式解包的变量,除非我有一个很好的理由(比如解决参考周期,如上所述)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM