Assigning to an optional variable in swift 3.0 using ? operator returns nil

☆樱花仙子☆ 提交于 2021-02-19 01:55:10

问题


Consider the following code.

var a:Int?

a? = 10

print(a)

Here the variable a isn't getting assigned the value 10. If it is because of the '?' operator, why compiler doesn't show a compilation error?.


回答1:


Try this

var a:Int?

a = 10

print(a)

Well...

? (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.

The main difference is that optional chaining fails gracefully when the optional is nil, whereas forced unwrapping triggers a runtime error when the optional is 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.



来源:https://stackoverflow.com/questions/43999142/assigning-to-an-optional-variable-in-swift-3-0-using-operator-returns-nil

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!