1

block在我的 Objective-C 代码中减慢了这个 s:

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

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

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 代码。现在我想ViewController在我的 swift 代码中使用这些代码。我使用下面的代码:

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到控制台,结果如下:

错误::3:1:错误:无法将类型“()->()”的值强制转换为类型“ActionStringDoneBlock”(又名“(可选,Int,可选)->()”)

我也尝试定义done如下:

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

    //My Codes

    }

但再次得到同样的错误。有人对快速代码中的问题有任何想法吗?

4

1 回答 1

5

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

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

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

没有注释的闭包被视为() -> (). 这就是错误消息所说的。

于 2017-07-11T09:40:48.530 回答