Swift generic method must use overloaded generic function
I am having trouble getting the desired effect using Swift generics. I have defined some common functions, but for specific cases I would like to override them to provide additional functionality. When I call functions from a non-generic method / function, everything works fine (it uses specific versions when the argument types are the same, and the generic version otherwise), but when I call functions from a generic method / function, it always uses the generic version functions (never specific versions).
Here's an example of a 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 (as it calls printSomething with a String argument all the time). Is there a way to do this without overloading each method / function with a specific version of String. Especially for the class case, because I can't overload the class methods for certain types of T?
source to share
This cannot currently be achieved for the reasons you mentioned yourself (you cannot overload instance / class methods for certain types <T>
).
However, instead of using function overloading, you can check the type at 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 performance impact should be negligible unless you call this function thousands of times.
source to share