I have the following quick code:
protocol Animal {
var name: String { get }
}
struct Bird: Animal {
var name: String
var canEat: [Animal]
}
struct Mammal: Animal {
var name: String
}
extension Array where Element: Animal {
func mammalsEatenByBirds() -> [Mammal] {
var eatenMammals: [Mammal] = []
self.forEach { animal in
if let bird = animal as? Bird {
bird.canEat.forEach { eatenAnimal in
if let eatenMammal = eatenAnimal as? Mammal {
eatenMammals.append(eatenMammal)
} else if let eatenBird = eatenAnimal as? Bird {
let innerMammals = eatenBird.canEat.mammalsEatenByBirds()
eatenMammals.append(contentsOf: innerMammals)
}
}
}
}
return eatenMammals
}
}
The compiler does not allow me to compile complaints:
Using "Animal" as a specific type matching the "Animal" protocol is not supported at the point where I call mammalsEatenByBirds () recursively
I saw some other answers, but could not connect my problem with any of them.
source
share