Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Type Erasure Magic

Type Erasure Magic

In a world where the Swift Protocol is King and Generics are our Queen, we seem to have trouble working with both together in perfect harmony. Is it possible for a hero to arise that can bring these two concepts together and make them work for us instead of against us?

Here's to hoping that Type Erasure can be that Hero.

In this talk I'll be explaining some shortcomings in Swift when working with Generics and Protocols and what type erasure is at a high level. Even more importantly, I'll explain why we need it when working with Protocols and Generics by giving a real world example of Type Erasure in an App Store app.

So far, a common question asked is why we would ever want to use Type Erasure in Swift. By the end of this talk I hope for the audience to have a better idea of how they can use generics and protocols together in their own applications and that type erasure can not only be easy, but useful.

Hector Matos

June 15, 2016
Tweet

More Decks by Hector Matos

Other Decks in Programming

Transcript

  1. protocol SpellDelegate { associatedtype SpellType func spell(spell: SpellType, hitEnemy enemy:

    Wizard) } class Spell { var delegate: SpellDelegate //ERROR } @allonsykraken
  2. Protocol SpellType can only be used as a generic constraint

    because it has Self or associated type requirements (˽°□°҂˽Ɨ ˍʓˍ @allonsykraken
  3. Closures are first-class citizens This means they can be passed

    as an argument, returned from a function, and assigned to a variable @allonsykraken
  4. Create a wrapper called Any* ! Make it generic! Make

    it conform to the generic protocol. Make it injectable ! Forward all calls to the injected type ⏩ Profit ! @allonsykraken