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?
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.
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.
In Swift, protocols contain multiple abstract members. Classes, structs and enums can conform to multiple protocols and the conformance relationship can be established retroactively.
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.)
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() { ... } }
You can use a composition of protocols
extension Serializable where Self: Model & Archivable { func fetch() { ... } }
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