【问题标题】:Assigning to an optional variable in swift 3.0 using ? operator returns nil在 swift 3.0 中使用?运算符返回 nil
【发布时间】:2017-10-15 09:33:52
【问题描述】:

考虑下面的代码。

var a:Int?

a? = 10

print(a)

这里的变量 a 没有被赋值 10。如果是因为 '?'运算符,为什么编译器不显示编译错误?

【问题讨论】:

  • 一般不要在赋值左侧的变量处使用感叹号和问号。
  • @Bibin P Sebastian 不过,你对 swift 中的可选 (?) 有什么困惑吗?
  • @Bibin P Sebastian 从技术上讲,您正在为可选解包的变量赋值。所以一个?评估为 nil 并且您正在尝试分配给 nil(即 nil = 10)。是否有意义。就编译器而言,它是一个有效的声明。

标签: swift optional


【解决方案1】:

试试这个

var a:Int?

a = 10

print(a)

嗯……

? (可选) 表示您的变量可能包含 nil 值,而 ! (unwrapper) 表示您的变量在运行时使用(试图从中获取值)时必须具有内存(或值)。

主要区别在于,当可选项为 nil 时,可选项链接会优雅地失败,而当可选项为 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.

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2018-05-09
    • 2017-02-20
    • 2017-11-03
    • 2017-04-24
    • 1970-01-01
    相关资源
    最近更新 更多