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? :)
Generic types are instantiated to form parameterized types by providing actual type arguments that replace the formal type parameters. A class like LinkedList<E> is a generic type, that has a type parameter E .
Pass the class object instead and it's easy. The idea here is that since you can't extract the type parameter from the object, you have to do it the other way around: start with the class and then manipulate the object to match the type parameter.
Mark the class init as required
and then call init :
class SuperBar {
required init() {
}
}
class Foo<T: SuperBar> {
func instantiateObject() -> T {
return T.init()
}
}
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