Is there a way to define a generic function in a protocol and allow the conforming object to define specializations for that protocol? For example:
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)
}
}
Now if I use the class like so:
let inst = Gen()
inst.generic(prop: 1, otherProp: "Go")
inst.generic(prop: "Hello", otherProp: "Stop")
I get the expected result of:
generic
Hello
However if I declare inst to be of type Generic:
let inst: Generic = Gen()
inst.generic(prop: 1, otherProp: "Go")
inst.generic(prop: "Hello", otherProp: "Stop")
I get:
generic
generic
So, if I have a property of type Generic, I am unable to use the specialization of the generic function from the implementor of the protocol. Is this expected behavior? Is there a way to achieve the behavior I am looking for, i.e. to use the specialization of the generic function even when accessed through the protocol's interface? I'd appreciate any insight into this. Thanks everyone.
f<T>(value: T)andf(value: String), they should have the same visible behavior for String; the latter just might be more efficient.