Alex Stone
Alex Stone

Reputation: 47338

iOS11 Swift 4 - how to check if Swift class conforms to protocol defined in Objective-C?

I have a legacy code base with code written in Objective-C. I'm adding a new class written in Swift which has to conform to existing protocols defined in Objective-C.

How can I make sure my Swift class correctly implements methods defined in Objective-C protocol?

//In Obj-C
    @protocol OBJCLocationObserver <NSObject>
    - (void)didUpdateLocationWithModel:(nullable Model *)locationModel
                       lastLocation:(CLLocationCoordinate2D)lastLocation;
    @end


//In Swift

    extension SwiftLocationManager : OBJCLocationObserver
    {
        public func didUpdateLocation(with model: Model?, lastLocation: CLLocationCoordinate2D) {
    // How to verify this function signature is actually conforming to the Obj-C protocol and is not a new method?
    }
    }

Upvotes: 0

Views: 1401

Answers (2)

Enea Dume
Enea Dume

Reputation: 3232

[MyClass conformsToProtocol:@protocol(MyProtocol)];

According to Apple Docs you can use conformsToProtocol:which returns a Boolean value that indicates whether the receiver conforms to a given protocol.


Example

@protocol MyProtocol
- (void)helloWorld;
@end

@interface MyClass : NSObject <MyProtocol>
@end

Will be exposed as:

console.log(MyClass.conformsToProtocol(MyProtocol)); 

var instance = MyClass.alloc().init();
console.log(instance.conformsToProtocol(MyProtocol))

Upvotes: 2

vacawama
vacawama

Reputation: 154573

Make sure you #import your protocol definition file into the <ProjectName>-Bridging-Header.h file:

#import "OBJCLocationObserver.h"

And then you should see error messages if your signature does not match.

You can also use Xcode Auto Completion. Type:

public func didUpdateLocation

and Auto Complete suggests:

public func didUpdateLocation(withModel Model?, lastLocation: CLLocationCoordinate2D)

which is different than what you have and explains why it isn't working.


Here is another way to get the interface:

As @MartinR suggested on a comment to another question:

Go to the header file where the protocol is defined, and choose "Generated Interface" from the "Related Items" popup in the top-left corner. That will show you the exact Swift method signature that you have to implement.

Upvotes: 2

Related Questions