Swift:方便初始化程序-在Self.init调用之前使用Self



我们在下面的便利方法上得到了以下错误:

Self.init调用之前已使用

class MyClass {
    var id : Int        
    var desc : String
    init?(id : Int, desc : String) {
        self.id = id
        self.desc = desc
    }
    convenience init?(id : Int?) {
        guard let x = id else {
            return
        }
        self.init(id : x, desc : "Blah")
    }
}

我们如何在Swift中实现这种类型的行为?

正如Leo已经指出的,安抚编译器的最快方法是在guard语句中返回nil。
convenience init?(id : Int?) {
    guard let x = id else {
        return nil
    }
    self.init(id: x, desc: "Blah")
}

除非有特定的原因,否则您也可以从一开始就避免使用故障初始化器。init(id : Int, desc : String)编译得很好。

最新更新