State & Binding

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

SwiftUI uses State and Binding to control how your views work and display information.

State: The Data Box

  • Stores Changing Information: Your State box holds information that might change, like the current score in a game, the state of a toggle switch, or text entered by the user.
  • Magic Update: Whenever the data in a State box changes, SwiftUI knows and automatically updates the parts of your screen that depend on that information.
@State var selectedAge: Double = 100

Binding: The Magic Pipeline

  • Connects Data and Views: Binding is like a magic pipeline connecting a State box (your data) to a view (like a text field, toggle, or slider).
  • Two-Way Flow:
Slider(value: $selectedAge, in: 0...255)

Working Together

  1. The slider starts by showing the value in the selectedAge data box (100).
  2. If the user moves the slider, the value in the selectedAge data box updates.
  3. If the data in the selectedAge data box changes, SwiftUI automatically updates the slider on the screen to reflect the change.
See forum comments
Download course materials from Github
Previous: Modifiers: Hands-On Demo Next: State & Binding: Hands-On Demo