Apple的
Swift language documentation表示可选绑定(a.k.a.如果允许)将“检查可选内部的值”并“将该值提取为变量或常量”.但这与我所看到的不符.例如
var x: Int? = nil if let y1: Int? = x { println("y1 = \(y1)") // This is printed,suggesting that x is not checked "inside",but left as Optional(nil) (!= nil) } if let y2: Int? = x? { println("y2 = \(y2)") } if let y3: Int = x? { println("y3 = \(y3)") } if let y4: Int = x { println("y4 = \(y4)") } if let y5 = x? { println("y5 = \(y5)") } if let y6 = x { println("y6 = \(y6)") }
结果(仅)
"y1 = nil"
建议在y1情况下不检查x的“内部”(并且x保留为包裹的nil,这不等于unwrapped nil). y2案例似乎通过强制“检查内部”(或者只是可选链接“接管”)来证实这一点;但是必须有更多的故事,因为y4和y6的情况也不打印,因此表现得好像正在发生“检查内部”.
我怀疑从尝试中获得了一些洞察力
"x = 42"
结果
"y1 = Optional(42)" "y2 = Optional(42)" "y3 = 42" "y4 = 42" "y5 = 42" "y6 = 42"
但如果三个人在那里,它就会丢失在我身上.
似乎(1)如果要求明确检查(带?),表达式右侧的“可选”确实会“内部检查”;但除此之外(2)表达式的左侧影响检查执行的“内部”程度(足以进行有效分配).
在这些情况下,可选绑定如何工作?特别是,当x == nil为什么y1打印,并且鉴于它确实如此,为什么不y4和y6(或生成赋值错误)?
我的解释不同:
var x: Int? = 1 if let y1: Int = x { println("y1 = \(y1)") } //prints y = 1,the optional was checked,contains a value and passes it var x: Int? = nil if let y1: Int = x { println("y1 = \(y1)") } //does not execute because x does not contain value that can be passed to a non optional y var x: Int? = nil if let y1: Int? = x { println("y1 = \(y1)") } // y = nil,since y is optional and can hold a value of x which is nil,then it passes nil
可选绑定用于检查可选项是否包含要传递给非可选参数的值.