SwiftUI State to Binding and Back Again

Marat Saytakov
1 min readDec 2, 2020

State-property can have didSet, and if mutated directly — will trigger it. But if State is passed as a Binding to another View, then…

Binding-property can have didSet, and if mutated directly — will trigger it. But at the same time — the original State’s didSet won’t be called. Even thou it has been also mutated!

Well, how to trigger an action in the original View with the original State-property when it’s been mutated?

I was impressed when I’ve found the solution, but it’s not that complicated. By the way the solution differs if you’re using old Swift or new Swift:

import SwiftUI
import Combine // import if using old Swift
struct ViewModel1: View {
@State var aText: String = "init" // B1
@State var catcher: Int = 0 // A1
var body: some View {
VStack {
View3(text: $aText)
View2(catcher: $catcher)
}
.onChange(of: catcher) { value in
aText = "catched (new Swift)"
}
.onReceive(Just(catcher)) { output in
aText = "catched (old Swift)"
}
}
}

It’s still not clear to me why State’s not triggering didSet, if their Binding has been updated. Cheers!

--

--