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

发布时间:2022-09-19 / 作者:清心寡欲
本文介绍了在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, selectedIndex:Int, selectedValue: Optional)  in

    //My Codes

    }

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

推荐答案

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

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

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

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

这篇关于在SWIFT中不能使用目标-C块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持吉威生活!



[英文标题]Can not use Objective-c block in swift


声明:本媒体部分图片、文章来源于网络,版权归原作者所有,如有侵权,请联系QQ:330946442删除。