Xcode beta 5 更新
最初提出的问题已在 Xcode beta5 中解决,这可能会使这个答案无效。
原答案
这可能需要进一步解释,为什么它肯定是不不一致行为但简单无效。
可选的value必须始终是right实际操作数一侧,并且不能位于left它的一侧。
通过两个简单的例子看看这个逻辑:
示例1
如果是这行代码:
self.window?.backgroundColor = UIColor.redColor()
< LEFT ^ RIGHT >
可选的位于left一边这意味着left侧面可能是nil
因此,在运行时,以下操作数将出现在此处:
nil = UIColor.redColor()
如果没有任何进一步或复杂的解释,这在每个层面上显然都是无效的 -nil
不能分配给其他东西,这就是编译器不允许它的原因。
NOTE:您可能会假设在以下情况下逻辑行为会是这样的self.window = nil
:
nil.backgroundColor = UIColor.redColor()
但有关的文档可选链接 https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html强调了一个非常重要的行为,它解释了为什么这种情况根本没有发生:
多个查询可以链接在一起,并且entire如果链中的任何环节被破坏,链就会优雅地失败nil
.
重点是这个词"entire",这就是为什么left侧面将是nil = ...
and not nil.backgroundColor = ...
正如你所期望的Objective-C.
示例2
另一个答案强调了如何解决它的另一个想法:
self.window?.setBackgroundColor(UIColor.redColor())
为什么这样有效?这里会不会有点不一致?当然不。
实际的可选是在right此处操作数的一侧,因为该行等于该行,但是我们不费心去获取void
在实践中根本没有。
let result: Void! = self.window?.setBackgroundColor(UIColor.redColor())
< LEFT ^ RIGHT >
as you see there is not any inconsistency at all here, because in the case of self.window = nil
that line would be equal to this one in runtime (please see the explanation above):
let result: Void! = nil
这将是一个完全合法的操作数。
逻辑很简单,可选必须始终位于right操作数(或运算符)的一侧,在left侧面它可以是非可选的value only.