迅捷方块不起作用 [英] Swift blocks not working
问题描述
我一直试图弄清楚如何快速使用JavaScriptCore.但是,当我不得不将块作为参数处理时,我遇到了问题,好像该块立即运行并且该参数获取了该块的返回值.我在做什么错了?
I've been trying to figure out how to use JavaScriptCore in swift. I'm running into problems however when I have to deal with blocks as arguments, seems like the block is run immediately and the arguments gets the return value of the block. What am I doing wrong?
工作目标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中的错误?
Am I missing something here, or is this just a bug in Swift?
我现在还尝试了铸封/块
class Block<T> {
let f : T
init (_ f: T) { self.f = f }
}
然后
ctx.setObject(Block<()->Void> {
/*code*/
}, forKeyedSubscript: "test")
此解决方案可让我编译,但会遇到运行时错误:
This solution lets me compile but I get a runtime error:
Thread 1: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0)
推荐答案
它与Swift实现闭包有关.您需要使用@convention(block)
注释闭包是ObjC块.使用unsafeBitCast
强制投射
It has something to do with how Swift implement closure. You need to use @convention(block)
to annotate that the closure is ObjC block. Use unsafeBitCast
to force cast it
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
这篇关于迅捷方块不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!