我发现了很多在 Swift 3 中使用 Singleton 模式的例子。我正在尝试使用这个方法:
class Records: RailsData {
static let shared = Records()
private init() {}
...
}
当我这样做时,我得到了编译器错误:
Overriding declaration requires an 'override' keyword
当我添加 override
关键字时,它会编译并且一切似乎都能正常工作。是否需要覆盖,因为我正在对 RailsData
进行子类化? RailData
是一个抽象类,因为它不是直接实例化的。我也没有让它成为单例。
我试图通过使用 override
修饰符来确保我以后不会被咬...
最佳答案
您没有做错任何事 ;) override
修饰符是必需的 因为您的RailsData
父类(super class)声明了一个指定的初始化程序 具有完全相同的签名:
class RailsData {
init() {...}
...
}
因此,override
修改在您的子类中是必需的。同样的事情也适用于继承的方法。来自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()
输出:
- SuperClass.init()
- SubClass.init(x: 123)
- SuperClass.init(x: 123)
- SubClass.init(x: 123)
抽象类。顺便说一下,Swift 中没有对抽象类 的直接语言支持。 — 也不在 Objective-C 中— 但至少 Cupertino is thinking about it ;) 目前,这样的概念只是框架作者等使用的软约定。
关于swift - 在 Swift 中覆盖父类(super class)初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44187264/