Assigns a publisher’s output to a property of an object.
SDKs
- iOS 13.0+
- macOS 10.15+
- Mac Catalyst 13.0+
- tvOS 13.0+
- watchOS 6.0+
- Xcode 11.0+
Framework
- Combine
Declaration
func assign<Root>(to keyPath: Reference Writable Key Path<Root, DeferredPublisher.Output>, on object: Root) -> Any Cancellable
Parameters
keyPath
A key path that indicates the property to assign. See Key-Path Expression in The Swift Programming Language to learn how to use key paths to specify a property of an object.
object
The object that contains the property. The subscriber assigns the object’s property every time it receives a new value.
Return Value
An Any
instance. Call cancel()
on this instance when you no longer want the publisher to automatically assign the property. Deinitializing this instance will also cancel automatic assignment.
Discussion
Use the assign(to:
subscriber when you want to set a given property each time a publisher produces a value.
For example, given a type My
with the property date
, the following code uses a Timer
to set the date
property once a second.
let cancellable = Timer.publish(every: 1, on: .main, in: .default)
.autoconnect()
.assign(to: \MyViewModel.date, on: viewModel)