是否可以在 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
}
如果您将结构替换为类,则此示例有效。
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 在他下面的评论中所指出的,另一个关键区别是类对象是通过引用传递的,而非类对象(如结构)是通过值传递的。
关于swift - "subclassing"通用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31465100/