Search code examples
swiftprotocolsswift-protocolsidentifiable

Protocol oriented Programming Swift - Identifiable


Lets say I want to model a fantasy-game with protocol oriented programming in swift. the code below produces the following error:

Protocol 'Character' 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 Character: Identifiable {
    var name: String {get}
    var maxHealt: Int {get}
    var healt: Int { get set }
}
extension Character {
    var id: String {return name}
    mutating func setHealth(newValue: Int) {
        healt = newValue
    }
}

protocol Fighter {
    var attackPower: Int { get }
}
extension Fighter {
    func attack(enemy: Character ) -> Character {
        var enemy = enemy
        enemy.setHealth(newValue: enemy.maxHealt - self.attackPower)
        return enemy
    }
}

Solution

  • You need to add generic constraints.

    extension Fighter {
        func attack<T: Character>(enemy: T ) -> T { //<-- Here
            var enemy = enemy
            enemy.setHealth(newValue: enemy.maxHealt - self.attackPower)
            return enemy
        }
    }