Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active August 29, 2015 14:04
Show Gist options
  • Save kristopherjohnson/e7f458044f15004b8676 to your computer and use it in GitHub Desktop.
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
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"
@joshaber
Copy link

joshaber commented Aug 6, 2014

FWIW, in a project let bark = barkingAnimal.bark() crashes the compiler 😿

@kristopherjohnson
Copy link
Author

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