英文:
Incompatible pointer types returning swift class from Obj-C function
问题
I have a swift protocol Fruit, a swift class Pear, and a method in an Objc-c file returning a pointer to Pear
protocol Fruit: NSObjectProtocol {
}
@objcMembers
class Pear: NSObject, Fruit {
init()
}
In an Obj-C file, I have
@protocol Fruit;
- (NSObject<Fruit> *)getFavoriteFruit {
return [[Pear alloc] init]; // <- Error here
}
The error I'm getting is:
Incompatible pointer types returning 'Pear *' from a function with result type 'NSObject
* _Nonnull'
How are these different?
英文:
I have a swift protocol Fruit, a swift class Pear, and a method in an Objc-c file returning a pointer to Pear<Fruit>.
protocol Fruit: NSObjectProtocol {
}
@objcMembers
class Pear: NSObject, Fruit {
init()
}
In an Obj-C file, I have
@protocol Fruit;
- (NSObject<Fruit> *)getFavoriteFruit {
return [[Pear alloc] init]; // <- Error here
}
The error I'm getting is:
> Incompatible pointer types returning 'Pear *' from a function with result type 'NSObject<Fruit> * _Nonnull'
How are these different?
答案1
得分: 2
一: 将以下行更改为:
@objc
protocol Fruit: NSObjectProtocol {
二: 删除以下行:
@protocol Fruit;
因为你的代码现在没有在 Objective-C 代码中使用 Swift 协议。你通过前向声明定义了一个不同的 Objective-C 协议名为 Fruit
。由于 Pear
符合 Swift 的 Fruit
协议,所以你的 Objective-C 代码失败,因为 Swift 的 Pear
实例不是符合不同的 Objective-C Fruit
协议的 NSObject
。
英文:
You need two changes in your code.
One: Change the line:
protocol Fruit: NSObjectProtocol {
to:
@objc
protocol Fruit: NSObjectProtocol {
Two: Remove the line:
@protocol Fruit;
As your code is now, you are not using the Swift protocol in your Objective-C code. You are defining (via forward declaration) a different Objective-C protocol named Fruit
. Since Pear
conforms to the Swift Fruit
protocol, your Objective-C code fails because the Swift Pear
instance isn't an NSObject
conforming to the different Objective-C Fuit
protocol.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论