如果我有两个协议,其关联类型恰好相同,例如
protocol Read {
associatedtype Element
func read() -> Element
}
protocol Write {
associatedtype Element
func write(a: Element)
}
然后我想有一个类从中读取整数并将字符串写入:
class ReadWrite: Read, Write {
func read() -> Int {
return 5
}
func write(a: String) {
print("writing \(a)")
}
}
但编译器抱怨并建议将String
更改为Int
。理想情况下,应该推断出类型,或者至少在我明确声明
associatedtype Read.Element = Int
associatedtype Write.Element = String
在ReadWrite
内。有什么工作吗?
受this question启发的解决方法是创建两个辅助协议
protocol ReadInt: Read {
associatedtype Element = Int
}
protocol WriteString: Write {
associatedtype Element = String
}
并让类继承这两个:
class ReadWrite: ReadInt, WriteString {
func read() -> Int {
return 5
}
func write(a: String) {
print("writing \(a)")
}
}
这似乎是编译,但我害怕跟着这样做。
我在Swift的问题跟踪器中找到了the issue。任何人都需要这个缺失的功能(像我一样)应该投票。
答案 0 :(得分:1)
另一种解决方法是创建第三个组合协议:
protocol ReadWrite {
associatedtype R
associatedtype W
func read() -> R
func write(a: W)
}
它并不漂亮,因为它迫使你重新声明协议成员,但它确实保持通用(你不仅限于String和Int)。