With a Combine Publisher
, I can use the following to call a closure whenever a value changes:
let cancellable = x.sink { value in … }
How can I achieve the same behaviour with a variable marked @State
or @Binding
?
With a Combine Publisher
, I can use the following to call a closure whenever a value changes:
let cancellable = x.sink { value in … }
How can I achieve the same behaviour with a variable marked @State
or @Binding
?
Update
The below answer doesn't seem to work anymore, instead one can use .onChange(of:)
instead on the property
.onChange(of: someProperty) { value in
//use new value for someProperty
}
You can use willSet
and didSet
as with any normal property
@State private var someProperty: String {
didSet {
}
willSet {
}
}