Passing a Swift protocol to an Objective-C pointer

Passing a Swift protocol to an Objective-C pointer

<em>Using XCode 10.1 / Swift 4.2.</em>

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"];


Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

How to use Objective C Cocoapods in Swift Framework

My swift framework has dependency of Objective C Framework. How do I use that ?

A guide to Object Detection with OpenCV and Swift

In this article, we’ll see how to create and launch a object detection algorithm using OpenCV and Swift

Swift vs. Objective-C: The trending up-and-comer vs. the dinosaur

I remember how pivotal it was when Swift was introduced at Apple’s 2014 WWDC (Worldwide Developers Conference). It was the talk of the town and all the devs I worked with couldn’t wait to try it out. The iOS community was buzzing and there was a lot of excitement around the new language.