此错误消息的原因是如果您的Array
声明有效,则会出现以下问题:
protocol SomeProtocol {
typealias T
func doSomething(something: T)
}
// has already some values
let a: Array<SomeProtocol> = [...]
// what type should be passed as parameter?
// the type of T in SomeProtocol is not defined
a[0].doSomething(...)
作为解决方法,您可以为任何类型创建一个通用包装器结构,SomeProtocol
以便您可以指定类型T
(如在 Swift 标准库 AnyGenerator、AnySequence、...中)。
struct AnySomeProtocol<T>: SomeProtocol {
let _doSomething: T -> ()
// can only be initialized with a value of type SomeProtocol
init<Base: SomeProtocol where Base.T == T>(_ base: Base) {
_doSomething = base.doSomething
}
func doSomething(something: T) {
_doSomething(something)
}
}
现在您使用类型数组[AnySomeProtocol<T>]
(替换T
为您想要的任何类型)并在附加元素之前将其转换为AnySomeProtocol
:
var array = [AnySomeProtocol<String>]()
array.append(AnySomeProtocol(someType))
// doSomething can only be called with a string
array[0].doSomething("a string")