2

In my code, I'm referring a protocol written in Objective-C in another protocol written in Swift like this:

// Objective-C
@protocol C
- (void)c;
@end

//Swift    
protocol A {
  var a : UIView { get }
}

extension A where Self: C {
  var a : UIView {
    return UIView()
  }

  func c() {
    // default implementation of c
    // self.a bla bla bla
  }
}
// Compiler will complain ViewController does not conform to C
class ViewController: UIViewController, A, C {
  //...
}

The problem is even though I provided default implementation of C in the protocol A, the ViewController seems unable to get it and the code won't compile due to the ViewController does not conform to C error. It would be fine if the protocol C is written in Swift.

In my actual project, the protocol C is from third party (GIDSignInDelegate) which I cannot simply rewrite them. It's a common usage if you want to build some abstraction upon other abstractions written in Objective-C.

I created a sample project here: https://github.com/linktoming/Protocol-Demo

iamdavidlam
  • 404
  • 5
  • 10
Mingming
  • 2,189
  • 20
  • 21
  • A related discussion is [Swift - extend existing protocols to implement another protocol with default implements](http://stackoverflow.com/questions/37326309/swift-extend-existing-protocols-to-implement-another-protocol-with-default-imp/37353146?noredirect=1#comment63499993_37353146) – Mingming Jun 26 '16 at 15:45
  • Swift protocol extensions are not available from Objective-C code. It seems to be inferring, in this case, that if the protocol was written from Objective-C, that it would be called from Objective-C, but it can't if the implementation is relying upon a default implementation in a Swift protocol extension. – Rob Jun 26 '16 at 16:14
  • Rather than implementing `A` as a protocol with an extension, you can implement it as a `UIViewController` subclass that conforms to `C`, and then have `ViewController` subclass from `A` instead of `UIViewController`. – Rob Jun 26 '16 at 17:00
  • @Rob right, that's one option. I used a similar approach of using a concrete class but using it as a member instead of parent class. I don't want to introduce non-VC related responsibility into VC. – Mingming Jun 27 '16 at 09:23

0 Answers0