Swift 3通过选择器将闭包传递给objc函数

时间:2016-11-02 10:21:49

标签: objective-c swift function closures selector

我想通过选择器通过另一个函数传递一个闭包。以下是我理想的做法:

@objc private func aFunction(_ firstParam: String, onComplete: (String) -> Void) {
    //..some internal codes
    onComplete("Done.")
}

func functionCaller(_ selectorString: String, paramString: String, onComplete: (String) -> Void) {
    let selector : Selector = NSSelectorFromString(selectorString)

    self.perform(selector, with: printString, with: onComplete)
}

functionCaller("aFunction:onComplete:", paramString: "anotherParameter", onComplete: { (_ myString String) -> Void in
    print(myString)
})

问题是当你尝试编译它时,Swift会给出一个名为" Segmentation Fault:11"

的错误

我找到了有问题的一行:

self.perform(selector, with: printString, with: onComplete)

当我将最后with: onComplete参数更改为String(也更改了相关函数参数)时,它正在工作。据我所知,问题是通过self.perform发送封闭呼叫不起作用,因为第一个功能是' @ objc'标记的功能(我把它放在了原因,否则执行选择器在Swift 3上不起作用)。

所以任何想法如何将函数或闭包传递给' @ objc'通过执行选择器标记功能?

2 个答案:

答案 0 :(得分:0)

尝试在您的函数

中使用Any代替String
func functionCaller(_ selectorString: String, paramString: String, onComplete: (Any) -> Void) {

    let selector : Selector = NSSelectorFromString(selectorString)
    let complete : Any = onComplete("complete")        
    self.perform(selector, with: complete)
}

functionCaller("aFunction:onComplete:", paramString: "anotherParameter", onComplete: { (_ myString ) -> Void in

    let string = myString as! String
    print(string)
})

我测试了它并在 Swift 3

中工作

答案 1 :(得分:-2)

让completionHandler :(任何) - > Void = {value in                     let js =“try {(callBackKey)('(value)');删除窗口。(callBackKey);} catch(e){};”                     (jsContext为?TYWKWebView)?. evaluateJavaScript(js,completionHandler:nil)                 }

let handlerDict:[String:Any] = [TYJSBridge.COMPLETION_HANDLER_KEY:completionHandler]

let _ = jsInterfaceObject.perform(sel,with:parameters,with:handlerDict)             }