I am implementing a class Foo
in Swift, that is supposed to instantiate objects of a given subclass of SuperBar
, e.g. Bar: SuperBar
. I really like generics in Swift, so I tried implementing it this way:
class Foo<T: SuperBar> {
func instantiateObject() -> T {
return T()
}
}
class SuperBar {
}
class Bar: SuperBar {
}
let foo = Foo<Bar>()
let obj = foo.instantiateObject()
You can run the code snippet in an Xcode Playground and observe that obj
is of type SuperBar
instead of Bar
, although it says Bar
when I Alt-click on the constant name.
Any Ideas? :)