假设以下玩具示例:
protocol AwesomeType: Equatable { var thingy: Int { get } } extension Array where Element: Equatable { func doThing { ... } } extension Array where Element: AwesomeType { func doThing { ... } } extension String: AwesomeType { var thingy: Int { return 42 } }
如果我有一个字符串数组 – [“Foo”,“Bar”,“Baz”] – 我在其上调用doThing(),将调用哪个实现?为什么?
我相信这是在编译时确定的;换句话说,它不是一个动态的调度.但它是如何确定的?感觉它类似于协议扩展的规则,但这是一个动态的调度情况……
解决方法
它会产生一个
error: ambiguous use of ‘doThing()’
使用简单修改的示例:
protocol AwesomeType: Equatable { } extension Array where Element: Equatable { func doThing() { print("array one") } } extension Array where Element: AwesomeType { func doThing() { print("array two") } } extension String: AwesomeType { } let arr = [ "Foo","Bar","Baz" ] arr.doThing()
编译器抱怨
error: ambiguous use of ‘doThing()’
note: found this candidate
func doThing() { print(“array one”) }note: found this candidate
func doThing() { print(“array two”) }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。