Beta 3 中有一个回归,导致如果 T 不是 Equatable 或 Comparable,则 Optional<T> 无法与 nil 进行比较。
这是由于删除了定义相等运算符的_Nil 类型而导致的错误。 nil 现在是文字。该错误已由 Chris Lattner 在Apple Dev Forums
上确认
一些解决方法:
你仍然可以使用.getLogicValue()
if launchOptions.getLogicValue() && ... {
或直接
if launchOptions && ... { //calls .getLogicValue()
或者你可以使用“Javascript object to boolean”解决方案
var bool = !!launchOptions
(第一个!调用getLogicValue并否定,第二个!再次否定)
或者,您可以自己定义这些相等运算符,直到他们修复它:
//this is just a handy struct that will accept a nil literal
struct FixNil : NilLiteralConvertible {
static func convertFromNilLiteral() -> FixNil {
return FixNil()
}
}
//define all equality combinations
func == <T>(lhs: Optional<T>, rhs: FixNil) -> Bool {
return !lhs.getLogicValue()
}
func != <T>(lhs: Optional<T>, rhs: FixNil) -> Bool {
return lhs.getLogicValue()
}
func == <T>(lhs: FixNil, rhs: Optional<T>) -> Bool {
return !rhs.getLogicValue()
}
func != <T>(lhs: FixNil, rhs: Optional<T>) -> Bool {
return rhs.getLogicValue()
}
例子:
class A {
}
var x: A? = nil
if x == nil {
println("It's nil!")
}
else {
println("It's not nil!")
}
但是,这种解决方法可能会导致其他微妙的问题(它可能与 Beta 2 中的 _Nil 类型类似,因为它会导致问题而被删除...)。