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 } }
Swift 4 allows multiple protocols to be called at once with the help of protocol composition.
Protocols let you describe what methods something should have, but don't provide the code inside. Extensions let you provide the code inside your methods, but only affect one data type – you can't add the method to lots of types at the same time.
In Swift, you can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of. For more details, see Protocol Extensions. Extensions can add new functionality to a type, but they can't override existing functionality.
Protocol extensions are different. You cannot “extend” a protocol because by definition a protocol doesn't have an implementation - so nothing to extend. (You could say that we “extend a protocol WITH some functionality”, but even an extended protocol is not something we can apply a function to.)
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 { // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With