Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protocol Extension in Swift Where Object Is a Class and conforms to a Protocol

Tags:

I have two protocols (Archivable and Serializable) and a class (Model) that is subclassed multiple times. Many of the subclasses implement either Archivable or Serializable (or both). I'd like to define a function on all children of Model that implement both Archivable and Serializable. Both of these work:

extension Serializable where Self: Model {   func fetch() { ... } } 

or

extension Serializable where Self: Archivable {   func fetch() { ... } } 

However I can't figure out how to extend where both protocols are required. Are there any other options outside of creating a third protocol that conforms to the first two?

like image 745
Kevin Sylvestre Avatar asked Oct 26 '15 22:10

Kevin Sylvestre


People also ask

What is protocol extension in 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. Note. Extensions can add new functionality to a type, but they can't override existing functionality.

Can a protocol conform to a protocol?

Any type that satisfies the requirements of a protocol is said to conform to that protocol. In addition to specifying requirements that conforming types must implement, you can extend a protocol to implement some of these requirements or to implement additional functionality that conforming types can take advantage of.

Can a struct conform to a protocol Swift?

In Swift, protocols contain multiple abstract members. Classes, structs and enums can conform to multiple protocols and the conformance relationship can be established retroactively.

Can we use extension for protocol types?

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


2 Answers

I think this should work:

extension Archivable where Self: Model, Self: Serializable {      func fetch() { ... }  } 

... or the other way around:

extension Serializable where Self: Model, Self: Archivable {      func fetch() { ... }  } 
like image 143
0x416e746f6e Avatar answered Oct 14 '22 00:10

0x416e746f6e


You can use a composition of protocols

extension Serializable where Self: Model & Archivable {     func fetch() { ... } } 
like image 22
Artemiy Shlesberg Avatar answered Oct 14 '22 01:10

Artemiy Shlesberg