将 Swift 协议传递给 Objective-C 指针
Passing a Swift protocol to an Objective-C pointer
使用 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"];
指定每个 Animal
实现者也实现 NSObject
的接口:@objc protocol Animal : NSObjectProtocol
您还可以将 ObjC 中的变量类型更改为 id<Animal>
。
使用 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"];
指定每个 Animal
实现者也实现 NSObject
的接口:@objc protocol Animal : NSObjectProtocol
您还可以将 ObjC 中的变量类型更改为 id<Animal>
。