Incompatible pointer types returning Swift class from Obj-C function.

huangapple go评论67阅读模式
英文:

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&lt;Fruit&gt; *)getFavoriteFruit {
  return [[Pear alloc] init]; // &lt;- Error here
}

The error I'm getting is:

> Incompatible pointer types returning 'Pear *' from a function with result type 'NSObject&lt;Fruit&gt; * _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.

huangapple
  • 本文由 发表于 2023年5月20日 23:47:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296059.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定