I'm having trouble getting the desired effect with Swift generics. I defined some generic functions, but for specific cases I would like to override them to provide additional features. When I call the functions from a non generic method/function everything works fine (it uses the specific versions when the argument types match and the generic version otherwise), but when I call the functions from a generic method/function it always uses the generic version of the function (never the specific versions).
Here's an example playground:
func printSomething <T> (something: T) {
println("This is using the generic version.")
println(something)
}
func printSomething(string: String) {
println("This is using the specific version.")
println(string)
}
func printSomeMoreThings <T> (something: T) {
printSomething(something)
}
class TestClass <T> {
var something: T
init(something: T) {
self.something = something
}
func printIt() {
printSomething(self.something)
}
}
printSomething("a")
println()
printSomeMoreThings("b")
let test = TestClass(something: "c")
println()
test.printIt()
This gives the following output:
This is using the specific version.
a
This is using the generic version.
b
This is using the generic version.
c
I would like it to use the specific version all the time (since it's calling printSomething with a String argument all the time). Is there a way to do this without overloading every method/function with a specific String version. Especially for the Class case, because I can't overload the class methods for specific types of T?
This currently cannot be achieved for reasons that you have mentioned yourself (you can't overload instance/class methods for specific types of <T>
).
However, instead of using function overloading, you can check the type during runtime and act accordingly:
func printSomething<T>(something: T)
{
if let somestring = something as? String
{
println("This is using the specific version.")
println(somestring)
return
}
println("This is using the generic version.")
println(something)
}
The impact on performance should be negligible unless you call this function thousands of times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With