SwiftUI State and Data Flow

Understanding of how to handle App State and Data update in SwiftUI

Pavlos Simas
3 min readJul 31, 2023
Photo by Gustas Brazaitis on Unsplash

Introduction to SwiftUI State

State is a crucial aspect of SwiftUI that represents the current data within the view. When state properties change, SwiftUI automatically updates the UI to reflect the new values. You use the @State property wrapper to define state properties.

import SwiftUI

struct ContentView: View {
@State private var count = 0
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increment") {
count += 1
}
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

In this example, we define a count state property using @State. When the “Increment” button is tapped, the count value increases, and SwiftUI automatically updates the Text view to reflect the new value.

Two-Way Data Binding with @Binding

@Binding is used for two-way data binding, where the parent view passes a value to a child view, and any changes to the child view’s value are reflected back to the parent view.

import SwiftUI

struct ContentView: View {
@State private var isOn = false
var…

--

--

Pavlos Simas

iOS Developer, with passion about Development, Marketing and Finance. Join Medium from the following link: https://simaspavlos.medium.com/membership