加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:59:46 所属栏目:百科 来源:网络整理
导读:这是我的代码: public class AT : Any { public init(n : Int) { print("A") } } public class B : AInt {}public class C : B {}let x = C(n: 123) 这无法编译并大喊这样的错误: repl.swift:9:9: error: 'C' cannot be constructed because it has no acc
这是我的代码:

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)????}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读