gpt4 book ai didi

ios - 从泛型类继承初始值设定项

转载 作者:搜寻专家 更新时间:2023-10-31 19:34:22 25 4
gpt4 key购买 nike

我看过一些关于这个问题的讨论,但还没有读到令人满意的解释。谁能告诉我为什么这不起作用?

class Parent<T> {

var data:T

init(data:T) {
self.data = data
}
}

class Child : Parent<Int> {}

let c = Child(data: 4)

最后一行报错:

'Child' 无法构造,因为它没有可访问的初始化器

我真的需要实现初始化器来调用 super 吗?

编辑:

为了提供一点上下文,真实的代码看起来更接近于下面。我有一个使用泛型的 Action 类,因为我有另一段代码可以将操作链接在一起,我想使用 Swift 的类型安全来确保可以链接操作。然后我有一堆子类类(例如 CustomAction)。我正在寻找一种方法来避免覆盖每个子类中的 init 方法。或者,我想了解为什么这是不可能的。

class Action<Input, Output> {

var cachedOutput:Output?

init(cachedOutput:Output?) {
self.cachedOutput = cachedOutput
}
}

protocol CustomInput {}
protocol CustomOutput {}

class CustomAction : Action<CustomInput, CustomOutput> {
}

最佳答案

是的,你真的需要覆盖 init 方法..

class Parent<T> {

var data:T

init(data:T) {
self.data = data
}
}

class Child<T> : Parent<T> {
override init(data: T) {
super.init(data: data)
}
}

let c = Child(data: 4) // Child<Int>
let c2 = Child(data: "alfa") // Child<String>

有什么错误...

// what is the type T ? it is undeclared!
class Child2: Parent2<T> {}
// how to specialize non-generic type Parent ? how to create it?
// i need an initializer in class Child3 ... Hm ...
class Child3: Parent<Int> {}

// cannot specialize non-generic type 'Parent'
class Child3: Parent<Int> {
override init(data: Int) {
super.init(data: data)
}
}
// So, Child3 must be of the same specialized type as Parent!!

这很糟糕,不是吗?看看我的最后一个例子!

class Parent<T> {

var data:T

init(data:T) {
self.data = data
}
}

class Child<Double> : Parent<String> {
init(data: Double) {
super.init(data: "\(data)")
}
}

let c = Child(data: 4) // Child<Int> !!!!!
let d = Child(data: true) // Child<Bool> !!!

在你的情况下,它的工作方式如下

class Parent<T> {

var data:T

init(data:T) {
self.data = data
}
}

class Child: Parent<String> {
init(data: Double) {
super.init(data: "\(data)")
}
}

let c = Child(data: 4)
print(c.dynamicType) // Child :-)

关于ios - 从泛型类继承初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34250254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com