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" |
FWIW, in a project let bark = barkingAnimal.bark()
crashes the compiler 😿
Bug report filed: http://www.openradar.me/17929884
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 triedlet bark = barkingAnimal.bark()
, the compiler crashed. I posted a question to the dev forums: https://devforums.apple.com/thread/239594