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)
Shouldn't they both contain 4? Can someone explain it?
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)
Shouldn't they both contain 4? Can someone explain it?
The line
var a: Int?
declares an optional variable with anil
value.The line
a? = 4
makes use of optional chaining to assign a value to the variablea
. But ifa
isnil
, the assignment isn't done. And this is your case sincea
is currentlynil
. You simply needa = 4
to assign the value of4
to the variablea
.Instead of ......... as as? is nil the entire statement won't run
do