0
0
Swiftprogramming~10 mins

Built-in property wrappers (@State, @Published) in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a state variable in a SwiftUI view.

Swift
struct ContentView: View {
    [1] var count = 0

    var body: some View {
        Text("Count: \(count)")
    }
}
Drag options to blanks, or click blank then click option'
A@State
B@Published
C@Binding
D@ObservedObject
Attempts:
3 left
💡 Hint
Common Mistakes
Using @Published inside a View struct instead of @State.
Forgetting the @ symbol before the property wrapper.
2fill in blank
medium

Complete the code to declare a published property in an ObservableObject class.

Swift
class Counter: ObservableObject {
    [1] var value = 0
}
Drag options to blanks, or click blank then click option'
A@Published
B@EnvironmentObject
C@Binding
D@State
Attempts:
3 left
💡 Hint
Common Mistakes
Using @State inside a class instead of @Published.
Not conforming the class to ObservableObject.
3fill in blank
hard

Fix the error in the code by choosing the correct property wrapper for a view model property.

Swift
struct ContentView: View {
    @StateObject var model = Counter()

    var body: some View {
        Text("Value: \(model.[1])")
    }
}
Drag options to blanks, or click blank then click option'
A@State
Bvalue
C@Published
Dvalue.value
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use @Published or @State when accessing the property.
Using nested property names incorrectly.
4fill in blank
hard

Fill both blanks to declare a published property and update it inside a class.

Swift
class TimerModel: ObservableObject {
    [1] var seconds = 0

    func tick() {
        seconds [2] 1
    }
}
Drag options to blanks, or click blank then click option'
A@Published
B=
C+=
D@State
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' instead of '+=' to increment.
Using @State inside a class instead of @Published.
5fill in blank
hard

Fill all three blanks to declare a state variable, update it, and display it in a SwiftUI view.

Swift
struct ClickCounter: View {
    [1] var count = 0

    var body: some View {
        VStack {
            Text("Count: \(count)")
            Button("Increment") {
                count [2] [3] 1
            }
        }
    }
}
Drag options to blanks, or click blank then click option'
A@State
B+
C+=
D@Published
Attempts:
3 left
💡 Hint
Common Mistakes
Using @Published instead of @State in a view.
Using '=' instead of '+=' to update the variable.