0
votes

I have a protocol written in Swift that should be conformed by several controllers and some of them are written in Objective-C. Not all of them need all methods from this Swift protocol so at first I decided to provide some methods with default implementation for making them 'optional' but in this case my Objective-C controllers don't recognize my Swift protocol. Did anyone face the same situation and did find a solution? Some sample of my code:

@objc public protocol SwiftProtocol: AnyObject {
         func requiredMethod()
         func optionalMethod()
}

extension SwiftProtocol {
    func optionalMethod() {}
}
@interface ObjClass ()<SwiftProtocol>

And I've got the error : (59, 1) Cannot find protocol declaration for 'SomeProtocol' Using @objc public in methods instead of extension gave the same result. TIA for your help!

1

1 Answers

1
votes

Objective-C protocols cannot have default implementations.

Objective-C protocols can have real optional methods/properties, unlike Swift protocols, which only have required methods/properties. The workaround for this in Swift is the use of a default implementation, however, sadly those cannot be seen in Objective-C.

I would suggest creating a pure Swift protocol and for all Objective-C classes that want to extend this, write the conformance in Swift, then create @objc wrapper functions in Swift that call the default protocol implementations - if it needs to be called, if it doesn't need to be called, simply ignore it.

Something along the lines of:

protocol SwiftProtocol {
    func requiredFunc()
    func optionalFunc()
}

extension SwiftProtocol {
    func optionalFunc() {}
}

@objc extension ObjcClass: SwiftProtocol {
    @objc func requiredFunc() {
        print("do something")
    }

    // This will call the default implementation - can be omitted if you don't need to call the default implementation from Objective-C
    @objc func objc_optionalFunc() {
        optionalFunc()
    }
}