I\'m trying cast and/or generate a variable based upon the specified generic type. I understand there is no type erasure in swift, but it doesn\'t seem like the generics pre
The problem is var instance = T() Initialisers are not virtual so the instance is always made with BaseClass()*. The following code uses a class function to work around the problem:
class BaseClass {
func printme() -> String {
return "I am BaseClass"
}
class func makeInstance() -> BaseClass
{
return BaseClass()
}
}
class DerivedClass : BaseClass {
override class func makeInstance() -> BaseClass
{
return DerivedClass()
}
override func printme() -> String {
return "I am DerivedClass"
}
}
class Util {
func doSomething() -> String {
var instance = T.makeInstance()
return instance.printme()
}
}
var util = Util()
println("\(util.doSomething())")
I changed the implementation of printme() only because the original code didn't print anything in a playground for some reason.
* I think this is still a bug.