2

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?

Div
  • 1,363
  • 2
  • 11
  • 28
  • @JoakimDanielson I was under the false impression that willSet/didSet do not work on property wrappers. If you make your comment into an answer, I will gladly accept! – Div Sep 12 '20 at 20:03
  • What are you trying to achieve by doing that? Who would subscribe to that if you could achieve that – New Dev Sep 12 '20 at 21:52
  • @NewDev Being able to subscribe to a State variable allows for both View code and non-View code to receive updates on the value. – Div Sep 14 '20 at 21:52

1 Answers1

3

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 {

    }
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • 1
    This is not called for some reason. I'm using Picker and binding of @State variable. – atereshkov Jan 17 '21 at 19:29
  • @atereshkov Yes this seems to have changed, you should look into using `.onChange(of: perform)`instead – Joakim Danielson Jan 18 '21 at 12:31
  • `.onChange(of: myPropertyName) { newValue in }` should be used on particular view instead of `didSet { }` on particular property in SwiftUI – Danil Oct 22 '22 at 19:10