Home > Blockchain >  how to extend the intersection of two protocols in swift
how to extend the intersection of two protocols in swift

Time:04-26

Trying to add helper functions for classes that conform to two different protocols

protocol A {
  func doA()
}
protocol B {
  func doB()
}
typealias AnB = A & B

extension AnB {   // causes error can not extend non-nominal type
  func doAnB()
  {
   doA()
   doB()
  }
}

Any way around this?

CodePudding user response:

Sadly, you cannot extend a composite protocol typealias.

extension A where Self: B {
  func doAnB() {
    doA()
    doB()
  }
}

CodePudding user response:

Try this method please.

protocol A {
    func doA()
}
protocol B {
    func doB()
}
protocol C: A, B{
    func doC()
}
extension ViewController: C {   // try this new one.
    func doC()
    {
        self.delegate?.doA()
        self.delegate?.doB()
    }
    func doA(){}
    func doB(){}
}
  • Related