Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend a protocol that satisfies Multiple Constraints - Swift 2.0

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 } } 
like image 378
Audrey Li Avatar asked Jun 29 '15 21:06

Audrey Li


People also ask

How many protocols can a Swift class adopt?

Swift 4 allows multiple protocols to be called at once with the help of protocol composition.

What is protocol and protocol extension in Swift?

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.

Can you extend a protocol Swift?

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.

Can we extend protocol?

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.)


1 Answers

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 {     // ...  } 
like image 190
ABakerSmith Avatar answered Sep 20 '22 17:09

ABakerSmith