ios - 无法在 swift 中使用 Objective-c block

标签 ios objective-c swift objective-c-blocks actionsheetpicker

我已经在我的 objective-c 代码中减速了这个 block :

typedef void(^ActionStringDoneBlock)(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue);
typedef void(^ActionStringCancelBlock)(ActionSheetStringPicker *picker);

我在 objective-c 中减速了这个 block 的一个实例,如下所示:

ActionStringDoneBlock done = ^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
    selectedVisa = (int) selectedIndex;
    if ([visaView.textField respondsToSelector:@selector(setText:)]) {
        [visaView.textField performSelector:@selector(setText:) withObject:selectedValue];
    }
};

并像下面这样使用这个实例:

    [ActionSheetStringPicker showPickerWithTitle:"myTitle"
                                        rows:visaData
                            initialSelection:initialSelection
                                   doneBlock:done
                                 cancelBlock:cancel
                                      origin:visaView.textField
 ];

我的项目同时使用了 swift 和 objective-c 代码。现在我想在我的 swift 代码中的新 ViewController 中使用这些代码。我使用以下代码:

let done = {(picker: ActionSheetStringPicker?, selectedIndex:Int, selectedValue: Any?)  in

    //My Codes

    }

    let cancel  = {
        (_ picker: ActionSheetStringPicker) -> Void in

    }

    ActionSheetStringPicker.show(withTitle: "My Title",
                                 rows: messageTitleData,
                                 initialSelection: initialSelection,
                                 doneBlock: done as ActionStringDoneBlock,
                                 cancel: cancel as! ActionStringCancelBlock,
                                 origin: messageTitle.textField
    )

但我在 swift 代码中遇到以下错误:

EXC_BREAKPOINT

我已将 done as ActionStringDoneBlock 的输出打印到控制台,我看到以下结果:

error: :3:1: error: cannot convert value of type '() -> ()' to type 'ActionStringDoneBlock' (aka '(Optional, Int, Optional) -> ()') in coercion

我还尝试如下定义 done:

  let done = {(picker: Optional<ActionSheetStringPicker>, selectedIndex:Int, selectedValue: Optional<Any>)  in

    //My Codes

    }

但又遇到了同样的错误。有人知道 swift 代码中的问题是什么吗?

最佳答案

您需要注释闭包类型并省略传递的类型

let done : ActionStringDoneBlock  = { (picker, selectedIndex, selectedValue)  in ... }

let cancel : ActionStringCancelBlock = { picker in ... }

如果没有注释,闭包将被视为 () -> ()。这就是错误消息所说的内容。

关于ios - 无法在 swift 中使用 Objective-c block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45030325/

相关文章:

ios - Firebase 引用调用未返回正确的对象(Swift)

objective-c - 在 iOS 中显示带有斜体字母和上标指数的公式

objective-c - CAOpenGLLayer 已裁剪图像

ios - 我如何从 NSLocale 获取具有各自货币和语言的国家列表?

ios - 应用程序启动动画仅在从 Xcode 运行时有效

ios - 在 Array of Dictionaries of array 中搜索一个值

objective-c - 单击 UIAlertview 上的按钮后,iOS 应用程序立即崩溃

objective-c - objective-c - 你如何使用 Mac OSX lion 中的恢复功能

ios - 如何使用CorePlot框架和swift 3制作折线图?

swift - swift 四舍五入到最接近的小数点后 .5