Kevin Sylvestre
Kevin Sylvestre

Reputation: 38012

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

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?

Upvotes: 23

Views: 18292

Answers (2)

Artemis Shlesberg
Artemis Shlesberg

Reputation: 308

You can use a composition of protocols

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

Upvotes: 7

0x416e746f6e
0x416e746f6e

Reputation: 10136

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() { ... }

}

Upvotes: 50

Related Questions