如下寫法在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方法中調(diào)用super.init之前,必須初始化所有屬性
所以,在調(diào)用super.init()之前改變它
self.director = director
例外:
可選屬性>具有默認(rèn)值的屬性>懶惰的財產(chǎn)
為什么我必須在調(diào)用super.init之前設(shè)置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