Bird
Raised Fist0
iOS Swiftmobile~15 mins

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

Choose your learning style10 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

Practice

(1/5)
1. What is the main purpose of the @State property wrapper in SwiftUI?
easy
A. To keep track of data that can change and update the UI automatically
B. To create a constant value that never changes
C. To store data permanently on the device
D. To define a function inside a view

Solution

  1. Step 1: Understand @State role

    @State is used to hold data that can change inside a SwiftUI view.
  2. Step 2: Connect data change to UI update

    When @State data changes, SwiftUI automatically refreshes the view to show the new data.
  3. Final Answer:

    To keep track of data that can change and update the UI automatically -> Option A
  4. Quick Check:

    @State updates UI on data change = B [OK]
Hint: Remember: @State means data changes update the screen [OK]
Common Mistakes:
  • Thinking @State stores permanent data
  • Confusing @State with constants
  • Using @State for functions
2. Which of the following is the correct way to declare a @State variable for an integer counter in SwiftUI?
easy
A. @State let counter: Int = 0
B. var @State counter: Int = 0
C. private var @State counter = 0
D. @State private var counter = 0

Solution

  1. Step 1: Check correct @State syntax

    The correct syntax places @State before the variable declaration and usually uses private for encapsulation.
  2. Step 2: Identify valid declaration

    @State private var counter = 0 uses '@State private var counter = 0' which is the recommended and correct form.
  3. Final Answer:

    @State private var counter = 0 -> Option D
  4. Quick Check:

    @State before var, private optional = D [OK]
Hint: Always put @State before 'var' and use private if needed [OK]
Common Mistakes:
  • Placing @State after var
  • Missing var keyword
  • Using let instead of var
3. Consider this SwiftUI code snippet:
struct ContentView: View {
  @State private var count = 0
  var body: some View {
    VStack {
      Text("Count: \(count)")
      Button("Add") {
        count += 1
      }
    }
  }
}
What happens when the "Add" button is tapped?
medium
A. The app crashes because count is private
B. The count increases but the Text does not update
C. The count increases by 1 and the Text updates to show the new count
D. Nothing happens because @State variables cannot change

Solution

  1. Step 1: Understand @State behavior on change

    When the button increments count, the @State variable changes.
  2. Step 2: UI updates automatically

    SwiftUI detects the change and refreshes the Text to show the new count value.
  3. Final Answer:

    The count increases by 1 and the Text updates to show the new count -> Option C
  4. Quick Check:

    @State change triggers UI update = C [OK]
Hint: @State changes always refresh the UI automatically [OK]
Common Mistakes:
  • Thinking private stops UI updates
  • Assuming UI won't refresh on state change
  • Believing @State variables are immutable
4. What is wrong with this SwiftUI code?
struct ContentView: View {
  @State var text: String
  var body: some View {
    TextField("Enter text", text: $text)
  }
}
medium
A. TextField cannot bind to @State variables
B. @State variables must have an initial value
C. The body property must return a Button, not TextField
D. @State cannot be used inside a struct

Solution

  1. Step 1: Check @State variable declaration

    @State variables must be initialized with a value when declared.
  2. Step 2: Identify missing initial value

    Here, 'text' has no initial value, causing a compile error.
  3. Final Answer:

    @State variables must have an initial value -> Option B
  4. Quick Check:

    @State needs initial value = A [OK]
Hint: Always give @State variables a starting value [OK]
Common Mistakes:
  • Forgetting to initialize @State variables
  • Thinking @State can't bind to TextField
  • Confusing struct rules with @State usage
5. You want to create a toggle switch that changes a text label between "On" and "Off" using @State. Which code snippet correctly implements this behavior?
hard
A. struct ContentView: View { @State private var isOn = false var body: some View { VStack { Toggle("Switch", isOn: $isOn) Text(isOn ? "On" : "Off") } } }
B. struct ContentView: View { var isOn = false var body: some View { VStack { Toggle("Switch", isOn: $isOn) Text(isOn ? "On" : "Off") } } }
C. struct ContentView: View { @State var isOn: Bool var body: some View { VStack { Toggle("Switch", isOn: $isOn) Text(isOn ? "On" : "Off") } } }
D. struct ContentView: View { @State private var isOn = false var body: some View { VStack { Toggle("Switch", isOn: isOn) Text(isOn ? "On" : "Off") } } }

Solution

  1. Step 1: Check @State declaration and initialization

    struct ContentView: View { @State private var isOn = false var body: some View { VStack { Toggle("Switch", isOn: $isOn) Text(isOn ? "On" : "Off") } } } correctly declares @State private var isOn = false, initializing the state.
  2. Step 2: Verify Toggle binding

    The Toggle uses $isOn to bind to the state variable, enabling UI updates on toggle.
  3. Step 3: Confirm Text updates with state

    The Text view uses a ternary to show "On" or "Off" based on isOn value.
  4. Final Answer:

    code correctly implements the toggle and text update -> Option A
  5. Quick Check:

    @State with $ binding updates UI = A [OK]
Hint: Use @State with $ for binding Toggle to update UI [OK]
Common Mistakes:
  • Not initializing @State variable
  • Missing $ for binding in Toggle
  • Declaring @State without initial value
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard