Swift optionals - Why does var a:Int? a? = 4 return nil

后端 未结 2 540
长发绾君心
长发绾君心 2021-01-12 16:18

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) 


        
相关标签:
2条回答
  • 2021-01-12 16:48

    Instead of ......... as as? is nil the entire statement won't run

    a? = 4       ==   nil = 4
    

    do

    a = 4
    
    0 讨论(0)
  • 2021-01-12 16:50

    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.

    0 讨论(0)
提交回复
热议问题