Swift块不工作

时间:2014-07-06 12:12:45

标签: swift block javascriptcore

我一直试图弄清楚如何在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)

2 个答案:

答案 0 :(得分:27)

它与Swift如何实现闭包有关。您需要使用@convention(block)来注释闭包是ObjC块。使用unsafeBitCast强制投射

var block : @convention(block) (NSString!) -> Void = {
   (string : NSString!) -> Void in 
    println("test")
}

ctx.setObject(unsafeBitCast(block, AnyObject.self), forKeyedSubscript: "test")

来自REPL

swift
Welcome to Swift!  Type :help for assistance.
  1> import Foundation
  2> var block : @convention(block)(NSString!) -> Void = {(string : NSString!) -> Void in println("test")}
block: @convention(block)(NSString!) -> Void =
  3> var obj: AnyObject = reinterpretCast(block) as AnyObject
obj: __NSMallocBlock__ = {} // familiar block type

答案 1 :(得分:1)

我有一个工作演示:

这是实现块注册的部分:

typealias ID = AnyObject!
extension JSContext {
    func fetch(key:NSString)->JSValue {
        return getJSVinJSC(self, key)
    }
    func store(key:NSString, _ val:ID) {
        setJSVinJSC(self, key, val)
    }
    func store(key:NSString, _ blk:()->ID) {
        setB0JSVinJSC(self, key, blk)
    }
    func store(key:NSString, _ blk:(ID)->ID) {
        setB1JSVinJSC(self, key, blk)
    }
    func store(key:NSString, _ blk:(ID,ID)->ID) {
        setB2JSVinJSC(self, key, blk)
    }
}

您需要一个非常小的objc代码和桥接标头才能使其正常工作。有关详细信息,请参阅存储库。