【发布时间】:2014-08-27 01:20:37
【问题描述】:
我一直在试图弄清楚如何在 swift 中使用 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:
var ctx = JSContext(virtualMachine:JSVirtualMachine())
let n: (string: String)->() = {string in /*code*/}
ctx.setObject(n, forKeyedSubscript:"test")
//Gives me "Type '(x: String) -> () does not conform to protocol 'AnyObject'"
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 non-@objc protocol type 'AnyObject'"
我在这里遗漏了什么,还是这只是 Swift 中的一个错误?
编辑:
我现在也尝试了Cast closures/blocks的建议
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)
【问题讨论】:
-
相似但不同。这个问题是关于处理你收到的作为返回值的块 from Objc 方法。这是关于将 Swift 闭包作为块传递 to Objc 方法。
标签: swift block javascriptcore