Created
March 2, 2016 06:01
-
-
Save norio-nomura/2505272860c7a13c4f97 to your computer and use it in GitHub Desktop.
AnyPokemon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Pokemon { | |
typealias PokemonType | |
func attack(move: PokemonType) | |
} | |
class Pikachu: Pokemon { | |
func attack(move: Int) { | |
print("pika") | |
} | |
} | |
class Hitokage: Pokemon { | |
func attack(move: Double) { | |
print("fire") | |
} | |
} | |
class AnyPokemon<PokemonType>: Pokemon { | |
let _attack: PokemonType -> Void | |
required init<U: Pokemon where U.PokemonType == PokemonType>(_ pokemon: U) { | |
_attack = pokemon.attack | |
} | |
func attack(move: PokemonType) { | |
_attack(move) | |
} | |
} | |
let pika = AnyPokemon(Pikachu()) | |
let hito = AnyPokemon(Hitokage()) | |
pika.attack(3) | |
hito.attack(3.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment