Bird
0
0

Identify the error in the following code snippet:

medium📝 Debug Q6 of 15
iOS Swift - State Management in SwiftUI
Identify the error in the following code snippet:
class UserSettings: ObservableObject {
  @Published var name = ""
}

struct ProfileView: View {
  @EnvironmentObject var settings: UserSettings
  var body: some View {
    Text("Name: \(settings.name)")
  }
}

// Usage
ProfileView()
A@EnvironmentObject should be replaced with @StateObject.
BProfileView is missing .environmentObject(UserSettings()) injection.
CUserSettings should not use @Published for name.
DText interpolation syntax is incorrect.
Step-by-Step Solution
Solution:
  1. Step 1: Check environment object injection

    ProfileView uses @EnvironmentObject but no .environmentObject() modifier is applied when creating ProfileView.
  2. Step 2: Verify other parts

    @Published is correct for observable properties, @EnvironmentObject is correct here, and Text interpolation syntax is valid.
  3. Final Answer:

    ProfileView is missing .environmentObject(UserSettings()) injection. -> Option B
  4. Quick Check:

    Missing injection causes runtime error [OK]
Quick Trick: Always inject environment objects when creating views [OK]
Common Mistakes:
  • Confusing @Published usage
  • Replacing @EnvironmentObject with @StateObject incorrectly
  • Misreading Text interpolation syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes