gpt4 book ai didi

objective-c - 将 Swift 协议(protocol)传递给 Objective-C 指针

转载 作者:搜寻专家 更新时间:2023-10-31 22:09:28 26 4
gpt4 key购买 nike

使用 XCode 10.1/Swift 4.2。

我正在尝试将符合 Swift 协议(protocol)的对象分配给 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> .

关于objective-c - 将 Swift 协议(protocol)传递给 Objective-C 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54408351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com