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

Consider the following code.

var a:Int?

a? = 10

print(a)

Here the variable a is not assigned the value 10. If this is due to '?' operator, why does the compiler not show a compilation error ?.

+4
source share
1 answer

try it

var a:Int?

a = 10

print(a)

Well...

? (Optional) indicates that your variable may contain nil, as well ! (unrapper) indicates that your variable should have memory (or a value) when it is used (trying to get a value from it) at runtime.

, , , , 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 not optional and show a compile time error

Apple Developer Committee.

0

Source: https://habr.com/ru/post/1677242/


All Articles