我有以下快速代码:
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
}
}
编译器不允许我编译抱怨: 在我递归调用函数 mammalsEatenByBirds()
时,不支持使用'Animal'作为符合协议'Animal'的具体类型我已经看到了其他一些答案,但无法将我的问题与其中任何一个联系起来。
答案 0 :(得分:7)
修复正在将Element: Animal
替换为Element == Animal
。