I am trying to provide a default implementation of protocol so it can satisfy multiple constraints from other protocols.
Given the following protocols:
public protocol Creature {
var name: String { get }
var canMove: Bool { get }
}
public protocol Animal: Creature {}
public protocol Moveable {
var movingSpeed: Double { get set }
}
public protocol Agend {
var aged: Int { get }
}
I'm able to extend using a single condition on Self
:
// all animals can move
extension Moveable where Self: Animal {
public var canMove: Bool { return true }
}
But how do I set constraints to provide a default Moveable
implementation for types that conform to both Animal
and Aged
protocols? Something like below? Or is there some "add" "or" option for the where clause?
// Pseudocode which doesn't work
extension Moveable where Self: Animal && Self: Aged {
public var canMove: Bool { return true }
}
You could use a protocol composition:
extension Moveable where Self: protocol<Animal, Aged> {
// ...
}
Or just add the conformances one after the other:
extension Moveable where Self: Animal, Self: Aged {
// ...
}