如果我有两个协议,其关联类型恰好相同,例如
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)") } }
这似乎是编译,但我害怕跟随这种方式的任何问题.
再次更新
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。