swiftcollectionsprotocolsidentifiable

Collections of Protocol Types - protocol oriented programming


I want a collection of a protocol type: in this case I want a variable "party" to be an array of type GameCharacter so I can put all things that conform to GameCharacter inside it.

the code below produces the following error:

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

what's the problem here? how to do it right?


protocol GameCharacter: Identifiable {
    var name: String {get}
    var maxHealt: Int {get}
    var healt: Int { get set }

    }

struct Warrior: GameCharacter, Fighter {
    var name: String
    var maxHealt: Int
    var healt: Int
    var armor: Armor
    var weapon: Weapon
    var resistence: Int
    var id: String {
        return name
    }
}

var party: [GameCharacter] <--- error

Solution

  • You should not inherit your protocol from Identifiable (which has generics) in this case, instead add id explicitly and then below (simplified) is compilable

    protocol GameCharacter {
        var id: String { get }     // << here !!
        var name: String {get}
        var maxHealt: Int {get}
        var healt: Int { get set }
        
    }
    
    struct Warrior: GameCharacter {
        var name: String
        var maxHealt: Int
        var healt: Int
        var resistence: Int
        var id: String {        // << here !!
            return name
        }
    }