简体   繁体   English

Swift-可以在调用闭包时设置self的值吗?

[英]Swift - Can I set the value of self when calling a closure?

TLDR : Is there a equivalent for JavaScript call or apply in Swift? TLDR :是否有等效的JavaScript call或在Swift中apply

Let's say I have Foo class that have an instance variable bar and a method baz that receives a closure as argument: 假设我有一个Foo类,它具有一个实例变量bar和一个方法baz ,该方法接收一个闭包作为参数:

class Foo {
  var bar: String = ""
  func baz(closure: (Void) -> Void) {
    closure()
  }
}

I want to change the self value inside the closure. 我想更改闭包内的self值。 So the code is executed by the Foo instance. 因此,代码由Foo实例执行。

Like this: 像这样:

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"

Is that possible? 那可能吗?

You can't access Foo's members in the closure in the way you've described, but what you can do is modify the closure to take an instance of Foo as an argument, and pass in self . 您不能以您所描述的方式访问闭包中的Foo成员,但是您可以做的是修改闭包以将Foo的实例作为参数,并传入self The result could look something like this. 结果可能看起来像这样。

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

Here's a generic type version, which looks closer to call in javascript. 这里有一个通用的版型,看起来更接近call在JavaScript。

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"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM