Swift块不工作

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...