这是一个示例游乐场:
protocol P {
associatedtype T
func getValue() -> T
}
class Foo: P {
func getValue() -> String {
return "hello"
}
}
class Bar {
func test<T: P>(_ o: T) {
print("Generic", o.getValue())
}
func test(_ o: Any) {
print("Any")
}
}
let foo = Foo()
let bar = Bar()
bar.test(foo)
Run Code Online (Sandbox Code Playgroud)
这输出:Any.
如果我删除Any版本test,则调用泛型方法.类Foo符合协议P,为什么Swift不选择泛型方法,因为它更具体?有没有办法调用通用的?