簡體   English   中英

Swift-可以在調用閉包時設置self的值嗎?

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

TLDR :是否有等效的JavaScript call或在Swift中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"

那可能嗎?

您不能以您所描述的方式訪問閉包中的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

這里有一個通用的版型,看起來更接近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