使用 XCode 10.1 / Swift 4.2。
我正在尝试将符合 Swift 协议的对象分配给 Objective-C 指针。以下代码是按预期编译和工作的最小示例,但它给了我以下警告:
如果分配给局部变量:Incompatible pointer types initializing 'NSObject<Animal> *__strong' with an expression of type 'id<Animal> _Nullable'
如果分配给存储的属性:
Incompatible pointer types assigning to 'NSObject<Animal> *' from 'id<Animal> _Nullable'
关于如何解决该警告而不只是使其静音的任何想法?
SWIFT代码:
@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 代码:
// 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"];