Swift 选项 - 为什么 var a:Int?一种?= 4 返回零 [英] Swift optionals - Why does var a:Int? a? = 4 return nil

查看:79
本文介绍了Swift 选项 - 为什么 var a:Int?一种?= 4 返回零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面代码中的print(a)打印nil?

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) 

它们不应该都包含 4 吗?有人能解释一下吗?

Shouldn't they both contain 4? Can someone explain it?

推荐答案

var a: Int? 行声明了一个带有 nil 值的可选变量.

The line var a: Int? declares an optional variable with a nil value.

a?= 4 使用可选链为变量 a 赋值.但是如果 anil,则赋值没有完成.这就是你的情况,因为 a 当前是 nil.您只需要 a = 44 的值分配给变量 a.

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.

这篇关于Swift 选项 - 为什么 var a:Int?一种?= 4 返回零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆