swift - 在 Swift 中覆盖父类(super class)初始值设定项

标签 swift compiler-errors singleton overriding initializer

我发现了很多在 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() 

输出:

  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 ;) 目前,这样的概念只是框架作者等使用的约定。

关于swift - 在 Swift 中覆盖父类(super class)初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44187264/

相关文章:

swift - 如何将此类激活给另一个

ios - 加载应用程序后从另一个类调用时,iOS 中的对话框窗口不显示

ios - 导航和标签栏下的 UIView

java - 是什么导致了 "Incompatible operand types"错误?

java - 无法将符号解析为JSONObject

ios - Swift 2.2 - ViewController 类型的值没有成员操作

c++ - 检查 std::unordered_set::find 结果的代码将无法编译

java - Spring:应在启动时加载初始化的单例

objective-c - 如何使用 NSCoding 加载 Objective C Singleton?

javascript - 记录前缀 - 使用非单例或其他方法