Why does print(a)
in the following code print nil?
var a:Int?
a? = 4
print(a) //prints nil
var b:Int? = 4
print(b) //prints optional(4)
The line var a: Int?
declares an optional variable with a nil
value.
The line a? = 4
makes use of optional chaining to assign a value to the variable a
. But if a
is nil
, the assignment isn't done. And this is your case since a
is currently nil
. You simply need a = 4
to assign the value of 4
to the variable a
.