0
0
iOS Swiftmobile~10 mins

@Published properties in iOS 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 property that automatically notifies views when it changes.

iOS Swift
class ViewModel: ObservableObject {
  [1] var count = 0
}
Drag options to blanks, or click blank then click option'
A@State
B@ObservedObject
C@Published
D@Binding
Attempts:
3 left
💡 Hint
Common Mistakes
Using @State instead of @Published inside ObservableObject.
Forgetting to mark the class as ObservableObject.
2fill in blank
medium

Complete the code to make the ViewModel class notify views about changes.

iOS Swift
class ViewModel: [1] {
  @Published var name = ""
}
Drag options to blanks, or click blank then click option'
AIdentifiable
BView
CStateObject
DObservableObject
Attempts:
3 left
💡 Hint
Common Mistakes
Using View or StateObject instead of ObservableObject for the class.
Not conforming to any protocol.
3fill in blank
hard

Fix the error in the code by completing the property declaration to notify views.

iOS Swift
class Settings: ObservableObject {
  [1] var isOn = false
  func toggle() {
    isOn.toggle()
  }
}
Drag options to blanks, or click blank then click option'
AAdd @Published before isOn
BAdd @State before isOn
CAdd @Binding before isOn
DAdd @ObservedObject before isOn
Attempts:
3 left
💡 Hint
Common Mistakes
Using @State or @Binding inside ObservableObject classes.
Not marking the property at all.
4fill in blank
hard

Fill both blanks to declare a published property and initialize it.

iOS Swift
class UserSettings: ObservableObject {
  [1] var username: String = [2]
}
Drag options to blanks, or click blank then click option'
A@Published
B"Guest"
C""
Dvar
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting @Published.
Initializing with empty quotes instead of a meaningful default.
5fill in blank
hard

Fill all three blanks to create a published integer property with a default value and a method to increment it.

iOS Swift
class Counter: ObservableObject {
  [1] var count: Int = [2]
  func increment() {
    count [3] 1
  }
}
Drag options to blanks, or click blank then click option'
A@Published
B0
C+=
D-=
Attempts:
3 left
💡 Hint
Common Mistakes
Using -= instead of += to increment.
Not marking count as @Published.