[Swift]Property 'self.director' not initialized at super.init call问题

如下写法在swift中会报错

class MedicItem {
    var name:String
    init(name:String) {
        self.name = name
    }
}

class Movie: MedicItem {
    var director: String
    init(name:String, director:String) {
        super.init(name: name)
        self.director = director

    } 
}

原因是:在任何init方法中调用super.init之前,必须初始化所有属性
所以,在调用super.init()之前改变它

 self.director = director

例外:

可选属性>具有默认值的属性>懒惰的财产

为什么我必须在调用super.init之前设置self.director

报价从Swift编程语言,它回答你的问题:

“Swift’s compiler performs four helpful safety-checks to make sure
that two-phase initialization is completed without error:”

Safety check 1 “A designated initializer must ensure that all of the
“properties introduced by its class are initialized before it
delegates up to a superclass initializer.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. 07000

你可能感兴趣的:([Swift]Property 'self.director' not initialized at super.init call问题)