swift – 具有相同关联类型名称的协议
发布时间:2020-12-14 04:31:12 所属栏目:百科 来源:网络整理
导读:如果我有两个协议,其关联类型恰好相同,例如 protocol Read { associatedtype Element func read() - Element}protocol Write { associatedtype Element func write(a: Element)} 然后我想有一个类从中读取整数并将字符串写入: class ReadWrite: Read,Write
如果我有两个协议,其关联类型恰好相同,例如
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.任何人都需要这个缺失的功能(像我一样)应该投票. 解决方法
另一个解决方法是创建第三个组合协议:
protocol ReadWrite { associatedtype R associatedtype W func read() -> R func write(a: W) } 它并不漂亮,因为它迫使你重新声明协议成员,但它确实保持通用(你不仅限于String和Int). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |