In Swift 2 I have the following protocols
protocol Fightable {
// return true if still alive, false if died during fight
func fight (other: Fightable) -> Bool
}
protocol Stats {
var defense: Int { get }
var attack: Int { get }
}
I can implement a protocol extension for Fightable to provide a shared implementation of fight
across all value types which conform to Stats
if I change the type signature of fight
to
func fight (other: Self) -> Bool
and implement an extension as
extension Fightable where Self : Stats {
func fight (other: Self) -> Bool {
return self.defense > other.attack
}
}
The problem with the above implementation is that it requires the value types to be the same (Human
s can't fight Goblin
s). My current goal is to implement a protocol extension that provides a default implementation of fight
for any combination of value types as long as they implement Stats.
The following code
extension Fightable where Fightable : Stats {
func fight (other: Fightable) -> Bool {
return self.defense > other.attack
}
}
Produces the error
Type 'Fightable' in conformance requirement does not refer to a generic parameter or associated type
How can I make sure the other Fightable type also conforms to Stats for this extension?
I'm using Xcode 7 beta 1.