【发布时间】:2020-10-26 08:06:12
【问题描述】:
我编写了一个自定义存储,它应该只支持符合某些协议的对象:
protocol MyBaseProtocol {
func baseMethod()
}
class Stor <ElementType : MyBaseProtocol> {
var storage = [ElementType]()
func addElement(_ element: ElementType) {
storage.append(element)
}
}
接下来我创建了一个子协议,并且只想存储符合子协议的对象:
protocol MyProtocol : MyBaseProtocol {
func method()
}
var otherStorage = Stor<MyProtocol>() //compilation error
class C1 : MyProtocol {
func method() {
}
func baseMethod() {
}
}
class S1 : MyProtocol {
func method() {
}
func baseMethod() {
}
}
otherStorage.addElement(C1())
otherStorage.addElement(S1())
我有一个错误:
Value of protocol type 'MyProtocol' cannot conform to 'MyBaseProtocol'; only struct/enum/class types can conform to protocols
如何创建一个 Stor 实例,它只能存储符合 MyBaseProtocol 的对象?
【问题讨论】:
标签: swift generics types swift-protocols type-constraints