加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用?分配给swift 3.0中的可选变量?运算符返回nil

发布时间:2020-12-14 04:27:38 所属栏目:百科 来源:网络整理
导读:请考虑以下代码. var a:Int?a? = 10print(a) 这里变量a没有被分配值10.如果是因为’?’运算符,为什么编译器不显示编译错误? 解决方法 试试这个 var a:Int?a = 10print(a) 好… ? (Optional) indicates your variable may contain a nil value while ! (unw
请考虑以下代码.

var a:Int?

a? = 10

print(a)

这里变量a没有被分配值10.如果是因为’?’运算符,为什么编译器不显示编译错误?

解决方法

试试这个

var a:Int?

a = 10

print(a)

好…

? (Optional) indicates your variable may contain a nil value while ! (unwrapper) indicates your variable must have a memory (or value) when it is used (tried to get a value from it) at runtime.

主要区别在于,当optional是nil时,可选链接会正常失败,而当optional可选为nil时,强制解包会触发运行时错误.

var defaultNil : Int?  // declared variable with default nil value
println(defaultNil) >> nil  

var canBeNil : Int? = 4
println(canBeNil) >> optional(4)

canBeNil = nil
println(canBeNil) >> nil

println(canBeNil!) >> // Here nil optional variable is being unwrapped using ! mark (symbol),that will show runtime error. Because a nil optional is being tried to get value using unwrapper

var canNotBeNil : Int! = 4
print(canNotBeNil) >> 4

var cantBeNil : Int = 4
cantBeNil = nil // can't do this as it's not optional and show a compile time error

Here is basic tutorial in detail,by Apple Developer Committee.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读