0
0
iOS Swiftmobile~15 mins

@State property wrapper in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Counter Screen
A simple screen with a number that increases each time you press a button. It uses @State to keep track of the number.
Target UI
-------------------
|   Counter App   |
-------------------
|                 |
|       0         |
|                 |
|  [ Increase ]   |
-------------------
Display a number starting at 0
Add a button labeled 'Increase'
When the button is tapped, the number increases by 1
Use @State property wrapper to store the number
Starter Code
iOS Swift
import SwiftUI

struct CounterView: View {
    // TODO: Add @State property here

    var body: some View {
        VStack(spacing: 20) {
            // TODO: Show the number here

            Button("Increase") {
                // TODO: Increase the number here
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)
        }
        .padding()
    }
}

struct CounterView_Previews: PreviewProvider {
    static var previews: some View {
        CounterView()
    }
}
Task 1
Task 2
Task 3
Solution
iOS Swift
import SwiftUI

struct CounterView: View {
    @State private var count = 0

    var body: some View {
        VStack(spacing: 20) {
            Text("\(count)")
                .font(.largeTitle)
                .accessibilityLabel("Current count")

            Button("Increase") {
                count += 1
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)
            .accessibilityLabel("Increase count button")
        }
        .padding()
    }
}

struct CounterView_Previews: PreviewProvider {
    static var previews: some View {
        CounterView()
    }
}

We use the @State property wrapper to create a variable count that SwiftUI watches for changes. When count changes, the view updates automatically to show the new number.

The Text view displays the current count. The Button increases the count by 1 each time it is tapped.

This simple example shows how @State helps keep UI and data in sync easily.

Final Result
Completed Screen
-------------------
|   Counter App   |
-------------------
|                 |
|       0         |
|                 |
|  [ Increase ]   |
-------------------
Tapping the 'Increase' button adds 1 to the number displayed
The number updates immediately on screen
Stretch Goal
Add a 'Reset' button that sets the count back to 0
💡 Hint
Add another Button below the 'Increase' button that sets the @State count variable to 0 when tapped