Swift func() 能否向 Objective-C 调用者返回多个值



如果我这样定义一个 Swift 函数:

func hilo (holeSize : Int, prompt : Int) -> (ballType : Int, ballColor : Int)) {
...
return (result1, result2)
}

有没有办法从 Objective-C 方法调用这个 Swift func? 我希望使用数组或字典从 Objective-C 调用 func 来接收 func 结果。

似乎找不到任何讨论此主题的 doco 或其他内容。

谢谢。

组(返回多个值的函数(在Objective-C中不受支持,但你可以使用块。

- (void)hilo:(int)holeSize prompt:(int)prompt callback:(void (^)(ballType : Int, ballColor : Int))result {
   ...
}

[self hilo:(int)holeSize prompt:(int)prompt callback:^(ballType : Int, ballColor : Int) {
   ....
}];

你不能。你必须重新设计你的 Swift 方法,以返回一个在 Objective-C 中有效的类型。

来自:Apple Inc. Using Swift with Cocoa 和 Objective-C. iBooks。

你可以访问类或协议中标有@objc属性的任何内容,只要它与Objective-C兼容。这不包括仅限 Swift 的功能,例如此处列出的功能:

  • 泛 型
  • 元组
  • 在 Swift 中定义的枚举
  • 在 Swift 中定义的结构
  • 在 Swift 中定义的顶级函数
  • 在 Swift 中定义的全局变量
  • 在 Swift 中定义的类型别名
  • 斯威夫特风格的可变参数
  • 嵌套类型
  • 柯里函数

例如,将泛型类型作为参数的方法或 返回元组将无法从 Objective-C 中使用

强调我的

@ikmal-ezzani的理想。 我做了一个实现细节如下:

迅捷代码:

func getResult(_ input: Int) -> (previous: Int, next: Int) {
    return (previous: input - 1, next: input + 1)
}
@objc class WrapClass: NSObject {
    @objc static func getResult(_ input: Int, callback: ((_ previous: Int, _ next: Int) -> Void)) {
        let (previous, next) = YourModel.getResult(input)
        callback(previous, next)
    }
}

对象 C 代码:

//to use in Object-C
__block NSInteger pre = 0;
__block NSInteger next = 0;
[WrapClass getResult:10 callback:^(NSInteger preValue, NSInteger nextValue) {
    pre = preValue;
    next = nextValue;
}];

最新更新