我已经在 Swift编写了一段时间,我想我必须放一个!我没有立即定义的所有let字段变量. 现在我注意到这段代码没有编译,我真的很惊讶?为什么是这样? class MyClass : Mapper { var a: Bool! re
现在我注意到这段代码没有编译,我真的很惊讶?为什么是这样?
class MyClass : Mapper {
var a: Bool!
required init?(_ map: Map) {
}
// Mappable
func mapping(map: Map) {
a <- map["a"]
}
}
let myClass = MyClass()
if myClass.a { // Compiler not happy
// Optional type 'Bool!' cannot be used as a boolean; test for '!= nil' instead
}
if true && myClass.a { // Compiler happy
}
if myClass.a && myClass.a { // Compiler happy
}
Apple Swift 2.2版
编辑
有些人指出为什么我使用let来获取永不改变的变量.我提到它是用于字段变量,但我缩短了示例.使用ObjectMapper(http://github.com/Hearst-DD/ObjectMapper)时,init中不会立即定义所有字段.这就是为什么它们都是可选的?或要求!
在Swift 1.0中,可以通过检查来检查可选变量optVar是否包含值:
if optVar {
println("optVar has a value")
} else {
println("optVar is nil")
}
在Swift编程语言中,Swift 1.1(日期为2014-10-16)的更新声明:
Optionals no longer implicitly evaluate to
truewhen they have a value andfalsewhen they do not, to avoid confusion when working with optionalBoolvalues. Instead, make an explicit check againstnilwith the==or!=operators to find out if an optional contains a value.
所以,你得到的荒谬的错误信息是因为Swift编译器正在解释你的:
if a {
}
意思是:
if a != nil {
}
并且它鼓励您测试nil以确定Optional a是否具有值.
也许Swift的作者将来会改变它,但是现在你必须明确地打开一个:
if a! {
}
或检查是否为真:
if a == true {
}
或(完全安全):
if a ?? false {
print("this will not crash if a is nil")
}
