考虑以下代码。
var a:Int?
a? = 10
print(a)
这里变量 a 没有被分配值 10。如果是因为“?”运算符,为什么编译器不显示编译错误?
Try this
var a:Int?
a = 10
print(a)
Well...
? (选修的)表示您的变量可能包含零值,而! (拆包器)指示您的变量在运行时使用(尝试从中获取值)时必须具有内存(或值)。
主要区别在于,当可选值为 nil 时,可选链接会正常失败,而当可选值为 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
这是 Apple 开发者委员会提供的详细基本教程。 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)