Bird
Raised Fist0
Swiftprogramming~20 mins

Built-in property wrappers (@State, @Published) in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Property Wrapper Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this SwiftUI @State example?

Consider this SwiftUI view code snippet. What will be printed to the console when the button is tapped once?

Swift
import SwiftUI

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

    var body: some View {
        Button("Tap me") {
            count += 1
            print("Count is now \(count)")
        }
    }
}
ACount is now 0
BNo output printed
CCount is now 1
DCount is now 2
Attempts:
2 left
💡 Hint

Remember @State stores a value that updates when changed.

❓ Predict Output
intermediate
2:00remaining
What happens when @Published property changes in this ObservableObject?

Given this Swift class, what will be printed when model.name = "Alice" is executed?

Swift
import Foundation
import Combine

class UserModel: ObservableObject {
    @Published var name: String = ""
}

let model = UserModel()
let cancellable = model.$name.sink { newName in
    print("Name changed to: \(newName)")
}

model.name = "Alice"
AName changed to: Alice
BNo output
CName changed to:
DRuntime error
Attempts:
2 left
💡 Hint

@Published triggers updates to subscribers when the property changes.

🔧 Debug
advanced
2:30remaining
Why does this SwiftUI view not update when @Published changes?

Look at this code. The view does not update when model.name changes. What is the cause?

Swift
import SwiftUI

class UserModel: ObservableObject {
    @Published var name = ""
}

struct ContentView: View {
    @ObservedObject var model = UserModel()

    var body: some View {
        Text(model.name)
    }
}

let model = UserModel()
model.name = "Bob"
AThe Text view cannot display @Published properties
BThe @Published property must be private
CThe model instance is not initialized
DThe model property in ContentView should be marked with @ObservedObject
Attempts:
2 left
💡 Hint

SwiftUI views must observe ObservableObject with @ObservedObject to update.

📝 Syntax
advanced
1:30remaining
Which option correctly declares a @State property in SwiftUI?

Choose the correct syntax to declare a @State property named isOn initialized to false.

A@State private var isOn = false
Bvar @State isOn = false
C@State var isOn: Bool = false
D@State let isOn = false
Attempts:
2 left
💡 Hint

@State properties are usually private vars.

🚀 Application
expert
3:00remaining
How to combine @Published and @State for shared data in SwiftUI?

You want a SwiftUI view to update when a shared model's property changes. The model uses @Published. Which approach correctly connects the model to the view's @State?

AUse @Published in the view instead of @State
BUse @ObservedObject for the model in the view and bind the property directly, not @State
CUse @StateObject for the model and ignore @Published properties
DDeclare the model as @State and access the @Published property inside
Attempts:
2 left
💡 Hint

Think about which property wrapper watches ObservableObject changes.

Practice

(1/5)
1. What is the main purpose of the @State property wrapper in SwiftUI?
easy
A. To mark properties in a class that notify other objects when changed
B. To create a constant value that never changes
C. To store local, simple data inside a view and update the UI when it changes
D. To handle network requests asynchronously

Solution

  1. Step 1: Understand what @State does

    @State is used to keep simple, local data inside a SwiftUI view.
  2. Step 2: Recognize its effect on UI

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

    To store local, simple data inside a view and update the UI when it changes -> Option C
  4. Quick Check:

    @State manages local view data = B [OK]
Hint: Remember: @State is for local view data that changes [OK]
Common Mistakes:
  • Confusing @State with @Published
  • Thinking @State is for class properties
  • Assuming @State handles network or async tasks
2. Which of the following is the correct way to declare a @Published property inside a Swift class?
easy
A. struct MyStruct { @State var count: Int = 0 }
B. struct MyStruct { @Published var count: Int = 0 }
C. class MyClass { @State var count: Int = 0 }
D. class MyClass { @Published var count: Int = 0 }

Solution

  1. Step 1: Identify where @Published can be used

    @Published is used inside classes that conform to ObservableObject, not structs.
  2. Step 2: Check syntax correctness

    class MyClass { @Published var count: Int = 0 } correctly declares a class with a @Published property and initializes it.
  3. Final Answer:

    class MyClass { @Published var count: Int = 0 } -> Option D
  4. Quick Check:

    @Published used in classes = A [OK]
Hint: Use @Published only inside classes, not structs [OK]
Common Mistakes:
  • Using @Published in structs
  • Confusing @State with @Published
  • Missing var keyword or initialization
3. Consider the following SwiftUI code snippet:
class Counter: ObservableObject {
    @Published var value = 0
}

struct ContentView: View {
    @StateObject var counter = Counter()
    var body: some View {
        VStack {
            Text("Count: \(counter.value)")
            Button("Increment") {
                counter.value += 1
            }
        }
    }
}
What will be displayed after tapping the "Increment" button twice?
medium
A. Count: 0
B. Count: 2
C. Count: 1
D. Count: 3

Solution

  1. Step 1: Understand the initial state

    The Counter class starts with value = 0. The view shows "Count: 0" initially.
  2. Step 2: Analyze button action and updates

    Each tap on "Increment" increases counter.value by 1. After two taps, value becomes 2, and the UI updates automatically.
  3. Final Answer:

    Count: 2 -> Option B
  4. Quick Check:

    2 increments update value to 2 [OK]
Hint: Each button tap adds 1; count updates automatically [OK]
Common Mistakes:
  • Forgetting @Published triggers UI update
  • Assuming @StateObject resets value
  • Counting taps incorrectly
4. Identify the error in this SwiftUI code snippet:
class Model: ObservableObject {
    @Published var text: String
    init() {}
}

struct ViewContent: View {
    @StateObject var model = Model()
    var body: some View {
        Text(model.text)
    }
}
medium
A. Missing initial value for @Published property 'text' in Model
B. Cannot use @StateObject with ObservableObject classes
C. Text view cannot display a String property
D. Model class should be a struct

Solution

  1. Step 1: Check property initialization

    The @Published property text is declared but not initialized, and the init() is empty.
  2. Step 2: Understand Swift requirement for properties

    All non-optional properties must have an initial value or be initialized in the constructor. Here, text lacks both.
  3. Final Answer:

    Missing initial value for @Published property 'text' in Model -> Option A
  4. Quick Check:

    Uninitialized property causes error = A [OK]
Hint: Always initialize @Published properties or provide init values [OK]
Common Mistakes:
  • Assuming @StateObject can't be used with ObservableObject
  • Thinking Text can't display String
  • Believing Model must be a struct
5. You want to create a SwiftUI app where a view shows a user's name that can be edited in a separate view. Which combination of property wrappers should you use to ensure the UI updates correctly when the name changes?
hard
A. Use @State in the main view and @Published in a shared ObservableObject class
B. Use @Published in both views
C. Use @State in both views
D. Use @StateObject in the editing view only

Solution

  1. Step 1: Understand data sharing between views

    When multiple views need to share and update data, use an ObservableObject class with @Published properties.
  2. Step 2: Use @State for local view data and @Published for shared data

    The main view can use @State for local state, but the shared user name should be in a class marked with @Published to notify changes.
  3. Final Answer:

    Use @State in the main view and @Published in a shared ObservableObject class -> Option A
  4. Quick Check:

    Shared data uses @Published; local uses @State [OK]
Hint: Shared data needs @Published; local view data uses @State [OK]
Common Mistakes:
  • Using @State only for shared data
  • Using @Published in structs or views directly
  • Not using ObservableObject for shared data
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