在swift中比较单个if结构中的非可选bool有什么问题
我已经在
Swift编写了一段时间,我想我必须放一个!我没有立即定义的所有let字段变量.
现在我注意到这段代码没有编译,我真的很惊讶?为什么是这样? 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版 编辑 解决方法
有点历史……
在Swift 1.0中,可以通过检查来检查可选变量optVar是否包含值: if optVar { println("optVar has a value") } else { println("optVar is nil") } 在Swift编程语言中,Swift 1.1(日期为2014-10-16)的更新声明:
所以,你得到的荒谬的错误信息是因为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") } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |