在下面的课程
class Foo { let _defaultValue = "N/A" let value: String init (dict: NSDictionary) { self.value = dict["bar"] as? String! ?? _defaultValue } }
编译因消息而失败
在初始化之前由闭包捕获的常量’self.value’
据我所知,没有运算符读取self.value,这个消息真的很混乱.
class Foo { let value: String init (dict: NSDictionary) { let _defaultValue = "N/A" self.value = dict["bar"] as? String! ?? _defaultValue } }
使_defaultValue声明并在构造函数中初始化关闭编译器抱怨并且程序正常工作!
怎么解释这样的事情?
解决方法
错误消息的原因是nil-coalescing运算符
被定义为
被定义为
public func ??<T>(optional: T?,defaultValue: @autoclosure () throws -> T) rethrows -> T
并在第二个参数上做一个“自动关闭”(为了获得
短路行为).所以
self.value = dict["bar"] as? String ?? _defaultValue
由编译器转换为
self.value = dict["bar"] as? String ?? { self._defaultValue }()
在这里,编译器抱怨因为之前捕获了self
完全初始化. (错误消息略有不同
在Swift 2和Swift之间3).
init(dict: NSDictionary){ let defValue = _defaultValue self.value = dict["bar"] as? String! ?? defValue }
或者你可以使它成为类的静态属性:
class Foo { static let _defaultValue = "N/A" let value: String init(dict: NSDictionary) { self.value = dict["bar"] as? String ?? Foo._defaultValue } }
或者替换?通过if语句:
class Foo { let _defaultValue = "N/A" let value: String init (dict: NSDictionary) { if let value = dict["bar"] as? String { self.value = value } else { self.value = _defaultValue } } }
附录:相关资源:
>在Swift论坛中的Autoclosure of self in initializers.
> SR-944 Cannot use ‘self’ in RHS of && before all properties are initialized错误报告.
从错误报告中引用:
Jordan Rose: This is true since && is implemented using @autoclosure,but it’s certainly suboptimal.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。