【发布时间】:2014-07-22 13:21:06
【问题描述】:
我想创建一个可以存储符合特定协议的对象的类。对象应存储在类型化数组中。根据 Swift 文档协议,可以用作类型:
因为它是一种类型,所以你可以在许多允许其他类型的地方使用协议,包括:
- 作为函数、方法或初始化程序中的参数类型或返回类型
- 作为常量、变量或属性的类型
- 作为数组、字典或其他容器中项目的类型
但是以下会产生编译器错误:
Protocol 'SomeProtocol' 只能用作通用约束,因为它具有 Self 或关联的类型要求
你应该如何解决这个问题:
protocol SomeProtocol: Equatable {
func bla()
}
class SomeClass {
var protocols = [SomeProtocol]()
func addElement(element: SomeProtocol) {
self.protocols.append(element)
}
func removeElement(element: SomeProtocol) {
if let index = find(self.protocols, element) {
self.protocols.removeAtIndex(index)
}
}
}
【问题讨论】:
-
在 Swift 中有一类特殊的协议,它不提供对实现它的类型的多态性。此类协议在其定义中使用 Self 或 associatedtype(Equatable 就是其中之一)。在某些情况下,可以使用类型擦除的包装器来使您的集合同态。以here 为例。
标签: ios swift generics swift-protocols