泛型类型的初始化器不会在swift中继承吗?

泛型类型的初始化器不会在swift中继承吗?,第1张

概述这是我的代码: 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: ' 这是我的代码:

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没有定义任何指定的初始化器,它应该自动继承它的所有超类指定的初始化器,来自A< Int>.但实际上它并没有看起来连接到我.

解决方法 那个怎么样 ??我尝试使用覆盖代码和super.init,这不是错误.我认为您不必使用泛型类型的init函数.

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

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

总结

以上是内存溢出为你收集整理的泛型类型的初始化器不会在swift中继承吗?全部内容,希望文章能够帮你解决泛型类型的初始化器不会在swift中继承吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1017757.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存