现在我注意到这段代码没有编译,我真的很惊讶?为什么是这样?
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
true
when they have a value andfalse
when they do not,to avoid confusion when working with optionalBool
values. Instead,make an explicit check againstnil
with 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") }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。