Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate an object of a generic type in Swift

Tags:

generics

swift

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? :)

like image 453
knl Avatar asked Aug 17 '14 06:08

knl


People also ask

Can you instantiate a generic type?

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 .

How do you find the class object of a generic type?

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.


1 Answers

Mark the class init as required and then call init :

class SuperBar {
    required init() {
    }
}


class Foo<T: SuperBar> {

    func instantiateObject() -> T {
        return T.init()
    }

} 
like image 65
Morteza Soleimani Avatar answered Feb 07 '23 04:02

Morteza Soleimani