Search code examples
swiftobjective-creturn-typeswift-protocols

Incompatible pointer types returning swift class from Obj-C function


I have a swift protocol Fruit, a swift class Pear, and a method in an Objc-c file returning a pointer to Pear.

protocol Fruit: NSObjectProtocol {
}

@objcMembers
class Pear: NSObject, Fruit {
  init()
}

In an Obj-C file, I have

@protocol Fruit;

- (NSObject<Fruit> *)getFavoriteFruit {
  return [[Pear alloc] init]; // <- Error here
}

The error I'm getting is:

Incompatible pointer types returning 'Pear *' from a function with result type 'NSObject<Fruit> * _Nonnull'

How are these different?


Solution

  • You need two changes in your code.

    One: Change the line:

    protocol Fruit: NSObjectProtocol {
    

    to:

    @objc
    protocol Fruit: NSObjectProtocol {
    

    Two: Remove the line:

    @protocol Fruit;
    

    As your code is now, you are not using the Swift protocol in your Objective-C code. You are defining (via forward declaration) a different Objective-C protocol named Fruit. Since Pear conforms to the Swift Fruit protocol, your Objective-C code fails because the Swift Pear instance isn't an NSObject conforming to the different Objective-C Fuit protocol.