有没有办法在协议中定义泛型函数,并允许符合对象定义该协议的特化?例如:
protocol Generic {
func generic<T>(prop: T, otherProp: String)
}
class Gen: Generic {
func generic<T>(prop: T, otherProp: String) {
print("generic")
}
func generic(prop: String, otherProp: String) {
print(prop)
}
}
现在如果我像这样使用这个类:
let inst = Gen()
inst.generic(prop: 1, otherProp: "Go")
inst.generic(prop: "Hello", otherProp: "Stop")
我得到了预期的结果:
generic
Hello
但是,如果我声明inst
是Generic
类型:
let inst: Generic = Gen()
inst.generic(prop: 1, otherProp: "Go")
inst.generic(prop: "Hello", otherProp: "Stop")
我明白了:
generic
generic
所以,如果我有Generic
类型的属性,我无法使用协议实现者的泛型函数的特化。这是预期的行为吗?有没有办法实现我正在寻找的行为,即使通过协议的接口访问时使用泛型函数的特化?我很欣赏对此的任何见解。感谢大家。