Protocol oriented Programming Swift - Identifiable

user14534957

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

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Protocol Oriented Programming in swift iOS

Swift expose the protocol to objc in protocol oriented programming

Protocol Oriented Programming Example not working in swift 3.0

Protocol Oriented Programming in Swift for custom components

WWDC Protocol-Oriented Programming in Swift session

Swift enum conformance to identifiable: Type doesn't conform to Identifiable protocol

How to confirm an enumeration to Identifiable protocol in Swift?

How to use protocol oriented programming to improve my Swift code?

What is Protocol Oriented Programming in Swift? What added value does it bring?

Swift Protocol Oriented Extensions

Protocol Oriented Programming and the Delegate Pattern

Protocol Oriented Programming Optional Functions

Swift Protocol-Oriented Programming: Can Protocol Extension Property Have Same Name As Base Class Property

Collections of Protocol Types - protocol oriented programming

SwiftUI - Custom Identifier with Identifiable Protocol

Protocol-Oriented Programming Extension variable init twice

Why is it necessary to refer to self for the Identifiable protocol?

Swift Conform to Identifiable with existing property

Is this a correct example to show the benefit of the protocol-oriented design of the Swift?

swift generic sequence with identifiable constraint on elements

Identifiable protocol in swiftUI... id property... var vs let

Future of Aspect Oriented Programming

@annotaion in Aspect Oriented Programming

OOP(Object Oriented Programming)

types in object oriented programming

R and object oriented programming

Facade in Object Oriented Programming

object oriented programming in android

Scala object oriented programming