问题
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