Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'Protocol' as a concrete type conforming to protocol 'Protocol' is not supported

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.

like image 594
Muhammad Ali Avatar asked May 07 '17 14:05

Muhammad Ali


People also ask

Can a protocol conform to a protocol?

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.

What is protocol conformance?

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.

What is concrete type in Swift?

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.

Can only be used as a generic constraint because?

Protocol can only be used as a generic constraint because it has Self or associated type requirements.


1 Answers

Fix is replacing Element: Animal with Element == Animal.

like image 187
Muhammad Ali Avatar answered Sep 28 '22 05:09

Muhammad Ali