我想指定一个协议来管理一些符合另一个协议的类型对象。像这样:
// Specify protocol
protocol ElementGenerator {
func getElements() -> [Element]
}
protocol Element {
// ...
}
// Implement
class FooElementGenerator: ElementGenerator {
func getElements() -> [FooElement] {
// Generate elements here
return [FooElement()]
}
}
class FooElement {
// ...
}
当试图编译这个时,我得到一个错误:
Type 'FooElementGenerator' does not conform to protocol 'ElementGenerator'
暗示候选人func getElements() -> [FooElement]
的类型不匹配() -> [FooElement]
,但它期望() -> [Element]
.
如何修复这种错误?
更新:
该解决方案似乎有效:
protocol ElementGenerator {
typealias T:Element
func getElements() -> [T]
}
protocol Element {
// ...
}
class FooElementGenerator: ElementGenerator {
typealias T = FooElement
func getElements() -> [T] {
return [T()]
}
}
class FooElement: Element {
// ...
}
但是当我尝试创建这样的变量时:
let a: ElementGenerator = FooElementGenerator()
出现一个新错误:
Protocol 'ElementGenerator' can only be used as a generic constraint because it has Self or associated type requirements