简体   繁体   中英

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

TLDR : Is there a equivalent for JavaScript call or apply in Swift?

Let's say I have Foo class that have an instance variable bar and a method baz that receives a closure as argument:

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

I want to change the self value inside the closure. So the code is executed by the Foo instance.

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 . 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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