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

后端 未结 2 539
长发绾君心
长发绾君心 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: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.

提交回复
热议问题