Menu
Coddy logo textTech

The @Binding Property

Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 39 of 50.

When a screen grows, you split it into smaller views. A child view that must change its parent's state declares a @Binding instead of owning the value:

struct VolumeControl: View {
    @Binding var volume: Int

    var body: some View {
        Stepper("Volume: \(volume)", value: $volume, in: 0...10)
    }
}

The parent keeps the @State and passes a binding to it with $:

struct ContentView: View {
    @State private var volume = 5

    var body: some View {
        VStack {
            VolumeControl(volume: $volume)
            Text(volume == 0 ? "Muted" : "Playing")
        }
    }
}

There is one value, owned by ContentView. The stepper in the child changes it through the binding, and the parent's text follows. @State owns a value; @Binding borrows one from somewhere else.

challenge icon

Challenge

Medium

ThemeToggle should switch the parent's darkMode. Change its property to a @Binding, bind its Toggle to it, and pass $darkMode from ContentView. The text must read Dark theme while the toggle is on.

Try it yourself

import SwiftUI

@main
struct CoddyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction to SwiftUI

Practice on your own: Swift playground