Swift 中与 nil 比较并返回 bool

Pri*_*ung 3 swift

更新:Xcode beta5 之后这个问题不再是问题

似乎 beta3 版本重构了“nil”在幕后的工作方式,但没有提供足够的文档。

我有这段代码在 beta2 中运行良好:

func hasLogin() -> Bool {
    return self.credentail != nil
}
Run Code Online (Sandbox Code Playgroud)

但在 beta3 中,我遇到了这个错误

Type 'NativeObject' does not conform to protocol 'NilLiteralConvertible'
Run Code Online (Sandbox Code Playgroud)

self.credential是“Credential”协议的可选值,由 NSObject 子类实现

@objc
protocol Credential: NSObjectProtocol, NSCoding {

}

var credentail: Credential?
Run Code Online (Sandbox Code Playgroud)

我可以通过像这样的双重否定来使其工作,但它看起来确实很荒谬

func hasLogin() -> Bool {
    return !(!self.credentail)
}
Run Code Online (Sandbox Code Playgroud)

这是 Swift 中的错误还是我做错了什么?

Wes*_*gne 5

Swift 用于将布尔值Bool中的非值转换为在语句中使用的秘密方法if是协议getLogicValue()的方法LogicValue(它Optional实现):

func hasLogin() -> Bool {
    return self.credential.getLogicValue()
}
Run Code Online (Sandbox Code Playgroud)