gpt4 book ai didi

swift block 不工作

转载 作者:搜寻专家 更新时间:2023-10-30 21:48:06 25 4
gpt4 key购买 nike

我一直在努力弄清楚如何在 swift 中使用 JavaScriptCore。我遇到了问题,但是当我必须将 block 作为参数处理时,似乎 block 立即运行并且参数获取 block 的返回值。我做错了什么?

工作 objective-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 block 。使用 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

关于 swift block 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24595692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com