TLDR :Swift中的JavaScript call
或apply
是否相同?
让我们说我有Foo
类,它有一个实例变量bar
和一个接收闭包作为参数的方法baz
:
class Foo {
var bar: String = ""
func baz(closure: (Void) -> Void) {
closure()
}
}
我想更改闭包内的self
值。因此代码由Foo
实例执行。
像这样:
let foo = Foo()
foo.baz {
// I want to be able to change bar value without calling foo.bar, like this:
bar = "Hello world"
}
// Then foo.bar would be "Hello world"
这可能吗?
答案 0 :(得分:4)
您无法以您所描述的方式访问闭包中的Foo成员,但您可以做的是修改闭包以将Foo的实例作为参数,并传入self
。结果看起来像这样。
class Foo {
var bar: String = ""
func baz(closure: (this: Foo) -> Void) {
closure(this: self)
}
}
let foo = Foo()
foo.baz { this in
this.bar = "Hello world"
}
print(foo.bar) // Hello world
答案 1 :(得分:0)
这是一个通用类型版本,在javascript中看起来更接近call
。
class Foo {
var bar: String = ""
}
func call<T>( this: T, closure: (T->Void) ){
closure(this)
}
let foo = Foo()
call(foo){ this in
this.bar = "Hello World"
}