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"];
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.
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.
You can not create an instance of protocol. But however you can refer an object in your code using Protocol as the sole type.
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.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With