Here is my code:
public class A<T : Any> {
public init(n : Int) {
print("A")
}
}
public class B : A<Int> {
}
public class C : B {
}
let x = C(n: 123)
This fails compilation and yells such error:
repl.swift:9:9: error: 'C' cannot be constructed because it has no accessible initializers
The following code can be compiled.
public class A {
public init(n : Int) {
print("A")
}
}
public class B : A {
}
public class C : B {
}
let x = C(n: 123)
Shouldn't requirement types specified generic types' initializers be inherited?
========Additional Below=======
“Superclass initializers are inherited in certain circumstances, but only when it is safe and appropriate to do so. For more information, see Automatic Initializer Inheritance below.”
---Apple Inc. “The Swift Programming Language (Swift 2)” iBooks.
And this
“However, superclass initializers are automatically inherited if certain conditions are met.”
“Assuming that you provide default values for any new properties you introduce in a subclass, the following two rules apply:” Rule 1 “If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.” Rule 2 “If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.”
When looking into the first code, subclass B
doesn't define any designated initializers,it should automatically inherits all of its superclass designated initializers, those from A<Int>
.But actually it didn't which seems wired to me.
A convenience initializer is a secondary initializer that must call a designated initializer of the same class. It is useful when you want to provide default values or other custom setup. A class does not require convenience initializers.
An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }
A convenience initializer must call another initializer from the same class. A convenience initializer must ultimately call a designated initializer.
How about that ?? I try to use override code and super.init, it 's not error. I think that you don't have to init function with generic types.
try to put override init function in class B and class C. Look like this,
public override init(n:Int) {
super.init(n: n)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With