我有以下快速代码:
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’的具体类型
我已经看到了其他一些答案,但无法将我的问题与任何问题联系起来.
解决方法
Fix正在用Element == Animal替换Element:Animal.