简体   繁体   中英

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
    }
}

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM