1

Trying to learn the Combine framework and this operator is popping up: \.

Subscribers.Assign(object: lastPostLabel, keyPath: \.text)

I don't know what to call it to search for it. Anyone have a reference?

NewEndian
  • 559
  • 2
  • 16
  • 4
    This is a Swift keyPath. There are plenty of articles about them. [Here is one of them](https://www.swiftbysundell.com/articles/the-power-of-key-paths-in-swift/) – Alladinian May 09 '20 at 11:56
  • 1
    Does anyone know how I could've searched SO for "\." without knowing the term, keypath? Cancel that: "backslash dot" gets you there. Apologies – NewEndian May 09 '20 at 17:02

1 Answers1

1

With with subscriber you can assign an output value of publisher to some object property using key path, like in below example

class ViewModel: ObservableObject {

    @Published var text: String = "loading" // property

    private var task: AnyCancellable?

    func fetch() {
        task = Just("done") // ... like long operation here
            .delay(for: 1, scheduler: RunLoop.main)
            .assign(to: \.text, on: self) // equivalent to self.text = "done"
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690