Bird
Raised Fist0
iOS Swiftmobile~5 mins

@State property wrapper in iOS Swift

Choose your learning style10 modes available
Introduction

The @State property wrapper lets your app remember and update values that can change over time. It helps your app update the screen automatically when data changes.

When you want to keep track of a button tap count and show it on the screen.
When you need to update a text field as the user types.
When you want to toggle a switch and change the UI based on its state.
When you want to show or hide parts of the screen based on user actions.
Syntax
iOS Swift
@State private var variableName: Type = initialValue
Use @State only inside SwiftUI views to hold simple, local data.
Mark the variable as private to keep it safe inside the view.
Examples
A boolean state to track if a switch is on or off.
iOS Swift
@State private var isOn: Bool = false
An integer state to count button taps.
iOS Swift
@State private var count: Int = 0
A string state to hold user input text.
iOS Swift
@State private var username: String = ""
Sample App

This app shows a button and a text label. Each time you tap the button, the number increases and the text updates automatically. This happens because count is marked with @State, so SwiftUI knows to refresh the screen when it changes.

iOS Swift
import SwiftUI

struct ContentView: View {
  @State private var count: Int = 0

  var body: some View {
    VStack(spacing: 20) {
      Text("Button tapped: \(count) times")
        .font(.title)
      Button("Tap me") {
        count += 1
      }
      .padding()
      .background(Color.blue)
      .foregroundColor(.white)
      .cornerRadius(8)
    }
    .padding()
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
OutputSuccess
Important Notes

Only use @State for simple, local data inside one view.

For sharing data between views, use other tools like @ObservedObject or @EnvironmentObject.

Changing a @State variable automatically refreshes the view to show the new data.

Summary

@State keeps track of changing data inside a SwiftUI view.

It automatically updates the screen when the data changes.

Use it for simple, local variables like counters, toggles, or text inputs.

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