在SWIFT中不能使用目标-C块

我已在目标c代码中降低了block%s的速度:

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

我在Objective-c中减速了blocks的一个实例,如下所示:

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
 ];

我的项目用户既有快速代码,也有Objective-c代码。现在,我想在我的快速代码中使用新的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
    )

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

exc_Breakpoint

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

Error::3:1:Error:无法在强制中将类型为‘()->()’的值转换为类型‘ActionStringDoneBlock’(又名‘(可选,Int,可选)->()’)

我还尝试定义done如下:

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

    //My Codes

    }

,但再次收到相同的错误。有人知道快速代码中有什么问题吗?


解决方案

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

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

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

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

相关文章