我一直在想如何在快速使用JavaScriptCore。但是,当我必须将块作为参数进行处理时,我遇到了问题,好像块立即运行并且参数获得块的返回值。我究竟做错了什么?快速块不能正常工作
工作目标C代码:
JSContext* context = [[JSContext alloc] initWithVirtualMachine:[[JSVirtualMachine alloc] init]];
context[@"test"] = ^(NSString *string) {
//code
};
我已经试过:
1:
var ctx = JSContext(virtualMachine:JSVirtualMachine())
var ctx["test"] = {(string:NSString)->() in /*code*/ }
//Gives me "'JSContext' does not have a member named 'subscript'"
2:
3:
var ctx = JSContext(virtualMachine:JSVirtualMachine())
let n: (string: String)->() = {string in /*code*/}
ctx.setObject(n as AnyObject, forKeyedSubscript:"test")
//Gives me "Cannot downcast from '(string: String) ->() to [email protected] protocol type 'AnyObject'"
我在这里错过了什么,或者这只是Swift中的一个错误?
class Block<T> {
let f : T
init (_ f: T) { self.f = f }
}
现在我也试着建议,然后
ctx.setObject(Block<()->Void> {
/*code*/
}, forKeyedSubscript: "test")
该解决方案让我编译,但我得到一个运行时错误:
Thread 1: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0)
似乎是这个问题:http://stackoverflow.com/questions/24586293/cast-closures-blocks。 –
它是相似但不同。这个问题是关于处理你从* Objc方法作为返回值*得到的块。这是关于传递Swift闭包作为块*到* Objc方法。 –