swift - 使用分配给 swift 3.0 中的可选变量?运算符返回 nil

标签 swift option-type

考虑以下代码。

var a:Int?

a? = 10

print(a)

这里变量 a 没有被赋值为 10。如果是因为 '?'运算符,为什么编译器不显示编译错误?。

最佳答案

试试这个

var a:Int?

a = 10

print(a)

嗯...

? (Optional) indicates your variable may contain a nil value while ! (unwrapper) indicates your variable must have a memory (or value) when it is used (tried to get a value from it) at runtime.

主要区别在于,当可选值为 nil 时,可选链接优雅地失败,而当可选值为 nil 时,强制解包会触发运行时错误。

var defaultNil : Int?  // declared variable with default nil value
println(defaultNil) >> nil  

var canBeNil : Int? = 4
println(canBeNil) >> optional(4)

canBeNil = nil
println(canBeNil) >> nil

println(canBeNil!) >> // Here nil optional variable is being unwrapped using ! mark (symbol), that will show runtime error. Because a nil optional is being tried to get value using unwrapper

var canNotBeNil : Int! = 4
print(canNotBeNil) >> 4

var cantBeNil : Int = 4
cantBeNil = nil // can't do this as it's not optional and show a compile time error

Here is basic tutorial in detail, by Apple Developer Committee.

关于swift - 使用分配给 swift 3.0 中的可选变量?运算符返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43999142/

相关文章:

swift - 有异常的动态 UITableViewCell 高度

string - 从 Swift 字符串中删除 2 个字符

swift -GCM : Don't display iOS remote push notification

swift - 当 ElementOfResult 被推断为 Optional 时,flatMap 不会过滤掉 nil

java - 如何将字符串文本添加到 orElse 和 .map

java - 这个在 Java 8 中使用 Optionals 的例子是否正确?你会如何重写它?

swift - 在 Swift 中使用具有相同变量名的可选绑定(bind)

java - Null-Check & isPresent - 名称不同但问题相同?

ios - UITableView 在我实现 `estimatedHeightForRowAt indexPath` 后崩溃?

swift - 存储在 Firestore 中的系统日期对象的行为将发生变化,您的应用程序可能会崩溃?