I have the following swift 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 let me compile complaining: Using 'Animal' as a concrete type conforming to protocol 'Animal' is not supported at the point where I recursively call the function mammalsEatenByBirds()
I have seen some other answers but could not relate my problem to any of those.
The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.
A protocol implementation conformance statement (PICS) is a structured document which asserts which specific requirements are met by a given implementation of a protocol standard.
concept concrete type in category swiftSwift makes this easier via type inference and can deduce concrete types when it makes sense. This way, you don't need to explicitly spell out every single variable, constant, and generic.
Protocol can only be used as a generic constraint because it has Self or associated type requirements.
Fix is replacing Element: Animal
with Element == Animal
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With