SwiftUI Key Differences Cheatsheet
@State vs @Binding
@State:
- Declares a local source of truth within a view.
- The view owns and controls the state.
Example:
@State private var isOn = false
@Binding:
- Binds a state from the parent view, allowing read-write access in the child.
Example:
@Binding var isOn: Bool
Usage:
Parent declares @State, passes it with $isOn to a child using @Binding.
@ObservedObject vs @StateObject
@ObservedObject:
- Used when the object is owned outside the view.
- Will recreate on every view reload.
@StateObject:
- Used when the view owns and manages the lifecycle of the object.
- Keeps the object alive across view reloads.
Example:
@ObservedObject var viewModel: MyViewModel
@StateObject private var viewModel = MyViewModel()
SwiftUI Key Differences Cheatsheet
List vs ForEach
List:
- Creates a scrollable list of views.
- Includes built-in styling.
ForEach:
- Iterates over a collection.
- Used inside stacks (VStack, HStack) or inside List.
Example:
List {
ForEach(items, id: \ .self) { Text($0) }
onAppear vs onReceive
onAppear:
- Called once when the view appears.
- Commonly used for setup or API calls.
onReceive:
- Listens for a Combine publisher and responds to each update.
Example:
.onAppear { fetchData() }
.onReceive(timer) { time in update(time) }
NavigationView vs NavigationStack
SwiftUI Key Differences Cheatsheet
NavigationView (iOS 13+):
- Older navigation container.
- Still used in apps targeting iOS 13-15.
NavigationStack (iOS 16+):
- Type-safe, supports programmatic navigation via path.
Example:
NavigationStack {
NavigationLink("Next", value: "Detail")
.navigationDestination(for: String.self) { value in
Text(value)