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

2020-03-19 06:30发布

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?

2条回答
家丑人穷心不美
2楼-- · 2020-03-19 07:02

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.

查看更多
爷的心禁止访问
3楼-- · 2020-03-19 07:03

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

a? = 4       ==   nil = 4

do

a = 4
查看更多
登录 后发表回答