Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active August 29, 2015 14:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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"
@kristopherjohnson
Copy link
Author

I wrote this in response to https://twitter.com/joshaber/status/496833803160416256

It's weird that the let canBark = barkingAnimal as CanBark line is needed, but when I tried let bark = barkingAnimal.bark(), the compiler crashed. I posted a question to the dev forums: https://devforums.apple.com/thread/239594

@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