swift - 来自泛型类型的初始化器不会在 swift 中被继承?

标签 swift generics initializer

这是我的代码:

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)

编译失败并报错:

repl.swift:9:9: error: 'C' cannot be constructed because it has no accessible initializers

可以编译出如下代码。

public class A { 
    public init(n : Int) { 
        print("A")
    } 
} 
public class B : A {
}
public class C : B {
}
let x = C(n: 123)

需求类型指定泛型类型的初始值设定项不应该被继承吗?

========下面有补充=======

“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.

还有这个

“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.”

查看第一个代码时,子类 B没有定义任何指定的初始化器,它应该自动继承它的所有父类(super class)指定的初始化器,那些来自 A<Int> 的.但实际上并没有,这对我来说似乎是有线的。

最佳答案

那个怎么样??我尝试使用override code和super.init,没有报错。我认为您不必使用泛型类型初始化函数。

尝试在 B 类和 C 类中放置 override init 函数。 看起来像这样,

public override init(n:Int) { super.init(n: n) }

关于swift - 来自泛型类型的初始化器不会在 swift 中被继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34525368/

相关文章:

c++ - 为什么类内初始化器只能使用 = 或 {}?

ios - 如何将 Parse PFFile 从一个应用程序移动到另一个应用程序?

swift - 如何满足包含初始值设定项的协议(protocol)?

swift - 核心数据一对多关系未正确/按预期保存

Java:实例泛型

generics - 在 Scala 中获取泛型类型的特定简单名称

scala - 如何在scala中设置类型参数绑定(bind)来为数字创建泛型函数?

swift - 我该如何处理这个初始值设定项?

ios - IPA 创建失败,运行 build-ios-bundle

ios - 如何删除特定单元格的模糊 View ?