Skip to content

Instantly share code, notes, and snippets.

@danimal141
Forked from gwengrid/TypeErasure.swift
Last active March 9, 2017 09:47
Show Gist options
  • Save danimal141/2a9dbe2c39ce8aff4a15 to your computer and use it in GitHub Desktop.
Save danimal141/2a9dbe2c39ce8aff4a15 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) { print("️--------Thunder Attack") }
}
class Charmander: Pokemon {
typealias PokemonType = Fire
func attack(move: Fire) { print("-------Fire Attack") }
}
class Raichu: Pokemon {
typealias PokemonType = Thunder
func attack(move: Thunder) { print("-------Thunder Attack") }
}
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> = AnyPokemon(Pikachu())
let raichu: AnyPokemon<Thunder> = AnyPokemon(Raichu())
let electricPokemon = [pikachu, raichu]
let charmander: AnyPokemon<Fire> = AnyPokemon(Charmander())
for pokemon in electricPokemon {
pokemon.attack(thunderAttack)
}
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