0
0
iOS Swiftmobile~10 mins

@ObservedObject 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 an observed object in a SwiftUI view.

iOS Swift
struct ContentView: View {
  @ObservedObject var viewModel = [1]()

  var body: some View {
    Text(viewModel.title)
  }
}
Drag options to blanks, or click blank then click option'
AMyViewModel
BString
CInt
DView
Attempts:
3 left
💡 Hint
Common Mistakes
Using a struct instead of a class for the observed object.
Forgetting to mark the class with ObservableObject protocol.
2fill in blank
medium

Complete the code to update the view when the observed object changes.

iOS Swift
class MyViewModel: ObservableObject {
  @Published var count = 0
}

struct ContentView: View {
  @ObservedObject var viewModel = MyViewModel()

  var body: some View {
    Button(action: {
      viewModel.count [1] 1
    }) {
      Text("Count: \(viewModel.count)")
    }
  }
}
Drag options to blanks, or click blank then click option'
A-=
B+=
C*=
D/=
Attempts:
3 left
💡 Hint
Common Mistakes
Using = instead of +=, which replaces the value instead of adding.
Using the wrong operator like -= which subtracts.
3fill in blank
hard

Fix the error in the observed object declaration to properly update the view.

iOS Swift
class Counter: ObservableObject {
  var value = 0
}

struct ContentView: View {
  @ObservedObject var counter = [1]()

  var body: some View {
    Text("Value: \(counter.value)")
  }
}
Drag options to blanks, or click blank then click option'
APublished
BObservableObject
CCounter
DStateObject
Attempts:
3 left
💡 Hint
Common Mistakes
Using the protocol name ObservableObject instead of the class name.
Using @StateObject instead of @ObservedObject in this context.
4fill in blank
hard

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

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

  func tick() {
    seconds [2] 1
  }
}
Drag options to blanks, or click blank then click option'
APublished
B+=
C-=
DState
Attempts:
3 left
💡 Hint
Common Mistakes
Using @State instead of @Published inside ObservableObject.
Using = instead of += which replaces the value.
5fill in blank
hard

Fill all three blanks to create an observed object, update a published property, and display it.

iOS Swift
class ScoreModel: ObservableObject {
  @[1] var score = 0

  func increase() {
    score [2] 10
  }
}

struct ScoreView: View {
  @ObservedObject var model = ScoreModel()

  var body: some View {
    VStack {
      Text("Score: \(model.[3])")
      Button("Add 10") {
        model.increase()
      }
    }
  }
}
Drag options to blanks, or click blank then click option'
APublished
B+=
Cscore
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong property name in the Text view.
Forgetting to mark the property with @Published.