Sunday, July 24, 2016

Bridging Existentials & Generics in Swift 2

Benjamin Encz:

In an earlier blog post I pointed out some incompatibilities between type information that is statically known at compile time (Generics) and type information that is dynamically available at runtime (Existentials).


Given a heterogenous list of different instances that can be persisted we want to automatically find & call the DAO based on the type of object we encounter.


The .Self member, which would refer to the concrete type of the existential doesn’t exist in Swift 2. However, we can access the concrete type of the existential using Self from within protocols & protocol extensions.

Using a clever inversion of control we can use that Self type from within the PersistedType protocol (which all persisted types implement) to dynamically specify the generic type parameter of our GenericDAO<T>:

Comments RSS · Twitter

Leave a Comment