Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"];
like image 396
agirault Avatar asked Jan 28 '19 18:01

agirault


People also ask

Can Swift protocol be used in Objective-C?

You can work with types declared in Swift from within the Objective-C code in your project by importing an Xcode-generated header file. This file is an Objective-C header that declares the Swift interfaces in your target, and you can think of it as an umbrella header for your Swift code.

Can a protocol inherit from a class Swift?

Protocols allow you to group similar methods, functions, and properties. Swift lets you specify these interface guarantees on class , struct , and enum types. Only class types can use base classes and inheritance from a protocol.

Can we create object of protocol Swift?

You can not create an instance of protocol. But however you can refer an object in your code using Protocol as the sole type.

What is a protocol OBJC?

Advertisements. Objective-C allows you to define protocols, which declare the methods expected to be used for a particular situation. Protocols are implemented in the classes conforming to the protocol.


1 Answers

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>.

like image 70
jscs Avatar answered Sep 18 '22 13:09

jscs