Bridging Existentials & Generics in Swift 2
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 usingSelf
from within protocols & protocol extensions.Using a clever inversion of control we can use that
Self
type from within thePersistedType
protocol (which all persisted types implement) to dynamically specify the generic type parameter of ourGenericDAO<T>
: