我想指定一個協議來管理符合另一個協議的某些類型的對象。就像這樣:在Swift中指定協議之間的關係
// 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]
。
這種錯誤怎麼解決?
UPDATE:
該解決方案似乎是工作:
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
測試在迅速1.2 – Shoaib
是的,這是解決方案。我想我正在考慮太複雜的事情,所以我錯過了這個簡單的想法。 – ULazdins