且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是什么导致“常量在初始化之前被闭包捕获"错误

更新时间:2022-06-15 08:55:36

错误消息的原因是nil-coalescing运算符 定义为

The reason for the error message is that the nil-coalescing operator is defined as

public func ??<T>(optional: T?, defaultValue: @autoclosure () throws -> T) rethrows -> T

并在第二个参数上执行自动关闭"(以获取 短路行为).所以

and does a "auto closure" on the second argument (in order to get a short-circuiting behaviour). So

self.value = dict["bar"] as? String ?? _defaultValue

由编译器转换为

self.value = dict["bar"] as? String ?? { self._defaultValue }()

,在这里编译器会抱怨,因为self是在之前捕获的 正在完全初始化. (错误消息略有不同 在Swift 2和Swift 3之间).

and here the compiler complains because self is captured before being fully initialised. (The error messages are slightly different between Swift 2 and Swift 3).

可能的解决方法.您可以先将属性分配给局部变量:

Possible workarounds. You can assign the property to a local variable first:

init(dict: NSDictionary){
    let defValue = _defaultValue
    self.value = dict["bar"] as? String! ?? defValue
}

或者您可以将其设为该类的静态属性:

Or you can make it a static property of the class:

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
        }
    }
}

附录:相关资源:

  • Autoclosure of self in initializers in the Swift forum.
  • SR-944 Cannot use 'self' in RHS of && before all properties are initialized bug report.

错误报告中的语录:

乔丹·罗斯(Jordan Rose):自&&是使用@autoclosure实现的,但肯定不是***选择.

Jordan Rose: This is true since && is implemented using @autoclosure, but it's certainly suboptimal.