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

Keep Calm and Type Erase On

Keep Calm and Type Erase On

Try!Swift 2016

Gwendolyn Weston

March 03, 2016
Tweet

More Decks by Gwendolyn Weston

Other Decks in Technology

Transcript

  1. A type is a classification that defines: • a set

    of values • and the legal operations on them
  2. class GenericClass<T> { ... } let object: GenericClass<T> // !

    struct GenericStruct<U> { ... } let object: GenericStruct<U> // !
  3. ! + <T> = " class GenericClass<T> { ... }

    let StringClass: GenericClass<String> // ! struct GenericStruct<T> { ... } let IntStruct: GenericStruct<Int> // !
  4. protocol Pokemon { typealias PokemonType func attack(move:PokemonType) } class Pikachu:

    Pokemon { func attack(move: Electric) { ⚡ } } class Charmander: Pokemon { func attack(move: Fire) { " } }
  5. ⾠! let pokemon: Pokemon Protocol Pokemon can only be used

    as a generic constraint because it has Self or associated type requirements
  6. let pokemon = Pikachu() vs. let pokemon: AnyPokemon <Electric> pokemon

    = AnyPokemon(Pikachu()) Pikachu is instantiated as type AnyPokemon <Electric>
  7. Recap • What is a type? • 2 kinds of

    types: concrete, abstract • Reification with type parameters • Type erasure
  8. Example class AnyPokemon <PokemonType>: Pokemon { private let _attack: ((PokemonType)

    -> Void) required init<U:Pokemon where U.PokemonType == PokemonType>(_ pokemon: U) { _attack = pokemon.attack } func attack(type:PokemonType) { return _attack(type) } }