How to extend a protocol that satisfies Multiple Constraints - Swift 2.0
As of the time of this post, the answer is using protocol<Animal, Aged>
.
In Swift 3.0, protocol<Animal, Aged>
is deprecated.
The correct usage in Swift 3.0 is:
extension Moveable where Self: Animal & Aged {
// ...
}
You can also combine the protocols with a typealias
. This is useful when you are using a combination of protocols in multiple places (avoids duplication and promotes maintainability).
typealias AgedAnimal = Aged & Animal
extension Moveable where Self: AgedAnimal {
// ...
}
Since Swift 3 you can use typealias
to create types that conform to multiple protocols:
typealias AgedAnimal = Animal & Aged
So your code would become:
extension Moveable where Self: AgedAnimal {
// ...
}
Or like this:
typealias Live = Aged & Moveable
extension Animal where Self: Live {
// ...
}
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 {
// ...
}