0
0
iOS Swiftmobile~10 mins

@EnvironmentObject for shared state 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 shared data model using @EnvironmentObject in SwiftUI.

iOS Swift
struct ContentView: View {
  @EnvironmentObject var model: [1]

  var body: some View {
    Text(model.title)
  }
}
Drag options to blanks, or click blank then click option'
AStateObject
BSharedDataModel
CObservedObject
DEnvironment
Attempts:
3 left
💡 Hint
Common Mistakes
Using @StateObject or @ObservedObject instead of @EnvironmentObject
Using a wrong type name that does not match the shared model
2fill in blank
medium

Complete the code to inject the shared model into the environment in the app's root view.

iOS Swift
MyApp()
  .environmentObject([1]())
Drag options to blanks, or click blank then click option'
ASharedDataModel
BContentView
CStateObject
DEnvironmentObject
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a view type instead of the model
Using property wrapper names instead of the model class
3fill in blank
hard

Fix the error in accessing the shared model property in a child view.

iOS Swift
struct DetailView: View {
  var model: [1]

  var body: some View {
    Text(model.title)
  }
}
Drag options to blanks, or click blank then click option'
A@EnvironmentObject SharedDataModel
B@ObservedObject SharedDataModel
C@StateObject SharedDataModel
DSharedDataModel
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the @EnvironmentObject wrapper
Using @StateObject or @ObservedObject in child views
4fill in blank
hard

Fill both blanks to update the shared model's property and notify views.

iOS Swift
class SharedDataModel: ObservableObject {
  @Published var title = "Hello"

  func updateTitle(to newTitle: String) {
    self.title [1] newTitle
  }
}

struct ContentView: View {
  @EnvironmentObject var model: SharedDataModel

  var body: some View {
    Button(action: {
      model.title [2] "Welcome"
    }) {
      Text("Change Title")
    }
  }
}
Drag options to blanks, or click blank then click option'
A=
B+=
C-=
D*=
Attempts:
3 left
💡 Hint
Common Mistakes
Using += or other operators that do not replace the value
Forgetting to assign the new value
5fill in blank
hard

Fill all three blanks to create a SwiftUI view that reads and updates shared state correctly.

iOS Swift
struct ProfileView: View {
  @EnvironmentObject var model: [1]

  var body: some View {
    VStack {
      Text(model.[2])
      Button("Update") {
        model.[3] = "Updated"
      }
    }
  }
}
Drag options to blanks, or click blank then click option'
ASharedDataModel
Btitle
DupdateTitle
Attempts:
3 left
💡 Hint
Common Mistakes
Using method names instead of property names
Using wrong property names that do not exist