objective-cswiftcompiler-warningsswift-protocolspointer-conversion

Passing a Swift protocol to an Objective-C pointer


Using XCode 10.1 / Swift 4.2.

I'm trying to assign an object that conforms to a Swift protocol to an Objective-C pointer. The following code is a minimal example that compiles and works as expected, but it gives me the following warnings:

If assigning to a local variable: Incompatible pointer types initializing 'NSObject<Animal> *__strong' with an expression of type 'id<Animal> _Nullable'

If assigning to a stored property: Incompatible pointer types assigning to 'NSObject<Animal> *' from 'id<Animal> _Nullable'

Any idea on how to address that warning without just silencing it?

Swift code:

@objc protocol Animal {
    var name: String { get }
}

@objc class Pig: NSObject, Animal {
    var name: String = "pig"
}

@objc class Cow: NSObject, Animal {
    var name: String = "cow"
}

@objc class Farm: NSObject {
    static func getAnimal(name: String) -> Animal? {
        // return some animal or nil
    }
}

Objective-C code:

// This code returns a valid pointer to a Pig object
// that is usable in objective-c, but it also triggers 
// the warning described above
NSObject<Animal>* animal = [Farm getAnimalWithName:@"pig"];

Solution

  • Specify that every Animal implementer also implements NSObject's interface: @objc protocol Animal : NSObjectProtocol

    You could also change the type of the variable in ObjC to id<Animal>.