Menu
Coddy logo textTech

True Or False State

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

State can be a Bool. toggle() flips it between true and false:

@State private var isOn = false

Button("Switch") {
    isOn.toggle()
}

The ternary operator picks a value from the state, so one view can show two versions:

Text(isOn ? "Light is on" : "Light is off")
    .foregroundStyle(isOn ? .yellow : .gray)

isOn ? a : b gives a when isOn is true and b otherwise. After each tap, the body runs again and both the text and the color follow the new value.

challenge icon

Challenge

Easy

Make the lamp work. Tapping Switch should flip isOn, and the text should read Light is on when isOn is true and Light is off when it is false.

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