Decodable 强制 super open class 来实现初始化器
Decodable forces super open class to implement the initializer
我得到了这个代码:
open class A: Decodable {
public init() {
}
}
open class B: A {
public override init() {
super.init()
}
open required init(from decoder: Decoder) throws {
fatalError("init(from:) has not been implemented")
}
}
而且万能的Xcode 9.4.1告诉我需要把requiered关键字前的open
改成public
。在我将 open
更改为 public
后,编译器告诉我需要将其更改为 open
。如果两个 class 都是 open
,如果没有我的超级 class A 显式实现所需的初始值设定项,我将无法正常工作,如 class B 中所示。为什么?
Decodable forces super open class to implement the initializer
如果您不继承超类所具有的必需初始化程序,那么您必须自己实现它。
必需的初始化程序
Write the required modifier before the definition of a class initializer to indicate that every subclass of the class must implement that initializer: <..>
You must also write the required modifier before every subclass implementation of a required initializer, to indicate that the initializer requirement applies to further subclasses in the chain.
You do not have to provide an explicit implementation of a required initializer if you can satisfy the requirement with an inherited initializer.
如何避免自己实施:
初始化程序继承
Rule 1
If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.
来源
我得到了这个代码:
open class A: Decodable {
public init() {
}
}
open class B: A {
public override init() {
super.init()
}
open required init(from decoder: Decoder) throws {
fatalError("init(from:) has not been implemented")
}
}
而且万能的Xcode 9.4.1告诉我需要把requiered关键字前的open
改成public
。在我将 open
更改为 public
后,编译器告诉我需要将其更改为 open
。如果两个 class 都是 open
,如果没有我的超级 class A 显式实现所需的初始值设定项,我将无法正常工作,如 class B 中所示。为什么?
Decodable forces super open class to implement the initializer
如果您不继承超类所具有的必需初始化程序,那么您必须自己实现它。
必需的初始化程序
Write the required modifier before the definition of a class initializer to indicate that every subclass of the class must implement that initializer: <..>
You must also write the required modifier before every subclass implementation of a required initializer, to indicate that the initializer requirement applies to further subclasses in the chain.
You do not have to provide an explicit implementation of a required initializer if you can satisfy the requirement with an inherited initializer.
如何避免自己实施:
初始化程序继承
Rule 1
If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.