Last active
August 29, 2015 14:04
-
-
Save kristopherjohnson/e7f458044f15004b8676 to your computer and use it in GitHub Desktop.
Function that takes an argument that must be a subclass of a specified class, and that subclass must implement a specified protocol
This file contains 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 CanBark { | |
func bark() -> String | |
} | |
class Animal { | |
func animalType() -> String { | |
return "Animal" | |
} | |
} | |
class Dog: Animal, CanBark { | |
override func animalType() -> String { | |
return "Dog" | |
} | |
func bark() -> String { | |
return "Woof" | |
} | |
} | |
func makeAnimalBark<T where T: CanBark, T: Animal>(barkingAnimal: T) -> String { | |
let animalType = barkingAnimal.animalType() | |
// let bark = barkingAnimal.bark() <-- Doesn't work. Why? | |
let canBark = barkingAnimal as CanBark | |
let bark = canBark.bark() | |
return "\(animalType) says \"\(bark)\"" | |
} | |
let dog = Dog() | |
makeAnimalBark(dog) // Dog says "Woof" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bug report filed: http://www.openradar.me/17929884