2017-05-25 77 views
2

我發現無數的例子在斯威夫特3.我試圖用這個方法使用Singleton模式:重寫超類的初始化

class Records: RailsData { 
    static let shared = Records() 
    private init() {} 
    ... 
} 

當我這樣做,我得到的編譯器錯誤:

Overriding declaration requires an 'override' keyword

當我添加override關鍵字時,它編譯和一切似乎工作。是否需要覆蓋,因爲我是繼承RailsDataRailData是一個抽象類,它不直接實例化。我也沒有讓它成爲單身人士

我想確保我不使用override修改得有點遲...

回答

1

你是不是做錯了什麼;)的override修飾符是需要因爲你RailsData超聲明一個指定初始化確切相同的簽名:

class RailsData { 
    init() {...} 
    ... 
} 

這樣,override改性是neces製成在你的子類中唾棄。同樣的事情也適用於繼承的方法。從The Swift Programming Language book

When you write a subclass initializer that matches a superclass designated initializer, you are effectively providing an override of that designated initializer. Therefore, you must write the override modifier before the subclass’s initializer definition. This is true even if you are overriding an automatically provided default initializer.

As with an overridden property, method or subscript, the presence of the override modifier prompts Swift to check that the superclass has a matching designated initializer to be overridden, and validates that the parameters for your overriding initializer have been specified as intended.

放心吧,你將不會被這個後來咬傷;)


激勵例如。要查看此初始化行動覆蓋,嘗試這個例子:

class SuperClass { 
    init(x: Int) { 
     print("3. SuperClass.init(x: \(x))") 
    } 
    convenience init() { 
     print("1. SuperClass.init()") 
     self.init(x: 123) // Will be overridden by subclass. 
    } 
} 

class SubClass: SuperClass { 
    override init(x: Int) { 
     print("2. SubClass.init(x: \(x))") 
     super.init(x: x) 
     print("4. SubClass.init(x: \(x))") 
    } 
} 

// Calls inherited convenience initializer. 
let sub = SubClass() 

輸出:

  1. SuperClass.init()
  2. SubClass.init(x: 123)
  3. SuperClass.init(x: 123)
  4. SubClass.init(x: 123)

抽象類。順便說一句,對於抽象類Swift沒有直接的,語言的支持 - 也沒有在Objective-C - 但至少Cupertino is thinking about it;)目前,這樣的概念僅僅是作爲框架,作者採用公約等