大佬教程收集整理的这篇文章主要介绍了swift – 具有相同关联类型名称的协议,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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 – 具有相同关联类型名称的协议全部内容,希望文章能够帮你解决swift – 具有相同关联类型名称的协议所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。