Skip to content

Instantly share code, notes, and snippets.

@gwengrid
Last active September 12, 2018 05:14
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save gwengrid/d8aacf2118fa12c9b475 to your computer and use it in GitHub Desktop.
Save gwengrid/d8aacf2118fa12c9b475 to your computer and use it in GitHub Desktop.
Example of type erasure with Pokemon
class Thunder { }
class Fire { }
protocol Pokemon {
typealias PokemonType
func attack(move:PokemonType)
}
struct Pikachu: Pokemon {
typealias PokemonType = Thunder
func attack(move: Thunder) { /*⚡️*/ }
}
class Charmander: Pokemon {
func attack(move: Fire) { /*🔥*/ }
}
class Raichu: Pokemon {
typealias PokemonType = Thunder
func attack(move: Thunder) { /*⚡️*/ }
}
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)
}
}
let thunderAttack = Thunder()
let fireAttack = Fire()
let pikachu: AnyPokemon<Thunder>
pikachu = AnyPokemon(Pikachu())
pikachu.attack(thunderAttack)
let raichu: AnyPokemon<Thunder>
raichu = AnyPokemon(Raichu())
raichu.attack(thunderAttack)
let electricPokemon = [pikachu, raichu]
for pokemon in electricPokemon {
pokemon.attack(thunderAttack)
}
let charmander: AnyPokemon<Fire>
charmander = AnyPokemon(Charmander())
charmander.attack(fireAttack)
@eonist
Copy link

eonist commented Mar 9, 2017

Awesome! Did you ever build something with type erasure?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment