是否可以在 swift 中子类化通用结构?
假设我们有一个结构:
struct Foo<T> {}
我想对其进行“子类化”以添加一些功能:
struct Something {}
struct Bar<F>: Foo<Something> { /*<<<= ERROR: Inheritance from non-protocol type 'Foo<Something>' */
let store: Something
let someF: F
}
如果将 struct 替换为 class,则此示例有效。
class Foo<T> {}
//struct Bar1<T>: Foo<T> { /* Inheritance from non-protocol type 'Foo<T>' */
// let name = "Bar"
//}
class Something {}
class Bar<F>: Foo<Something> { /* Inheritance from non-protocol type 'Foo<Something>' */
let store: F?
init(value: F?) {
self.store = value
}
}
知道如何使其适用于结构吗?
我试图坚持使用值类型,但 swift 让它变得很困难。
我的理解是继承是类和非类对象(如 swift 中的结构和枚举)之间的主要区别。类具有继承性,其他对象类型则没有。
因此,我认为答案是“不,不是现在,也不是永远,按照设计。”
正如 Ammo 在下面的评论中指出的,另一个关键区别是类对象是通过引用传递的,而非类对象(如结构)是通过值传递的。
由于像
struct
这样的值类型不可能继承,所以我会这样构建它:
struct Foo<T> { //... }
struct Bar<T> {
let store: Something
let someT: T
}
然后使用组合来构建它们:
struct FooBar {
let foo: Foo<SomethingFoo>
let bar: Bar<SomethingBar>
}