Bird
Raised Fist0
iOS Swiftmobile~20 mins

@EnvironmentObject for shared state in iOS Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
EnvironmentObject Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
What will be displayed when the button is tapped?
Consider this SwiftUI code where a shared counter is updated using @EnvironmentObject. What text will appear after tapping the button once?
iOS Swift
class Counter: ObservableObject {
  @Published var count = 0
}

struct ContentView: View {
  @EnvironmentObject var counter: Counter
  var body: some View {
    VStack {
      Text("Count: \(counter.count)")
      Button("Increment") {
        counter.count += 1
      }
    }
  }
}
ACount: 0
BCount: 2
CApp crashes due to missing environment object
DCount: 1
Attempts:
2 left
💡 Hint
Remember that tapping the button increases the count by 1 and the view updates automatically.
❓ lifecycle
intermediate
2:00remaining
What happens if @EnvironmentObject is not injected?
Given a SwiftUI view that uses @EnvironmentObject but the environment object is not provided in the view hierarchy, what will happen when the app runs?
iOS Swift
class UserSettings: ObservableObject {
  @Published var username = "Guest"
}

struct ProfileView: View {
  @EnvironmentObject var settings: UserSettings
  var body: some View {
    Text("User: \(settings.username)")
  }
}
AThe app crashes at runtime with a fatal error
BThe Text shows 'User: Guest' by default
CThe Text shows empty string
DThe app compiles but the view does not update
Attempts:
2 left
💡 Hint
Think about what happens if the environment object is missing when the view tries to access it.
🧠 Conceptual
advanced
2:00remaining
How does @EnvironmentObject differ from @ObservedObject?
Which statement correctly describes the difference between @EnvironmentObject and @ObservedObject in SwiftUI?
A@EnvironmentObject is injected automatically from the environment, while @ObservedObject requires manual passing of the object.
B@ObservedObject is used only for local state, @EnvironmentObject only for global constants.
C@EnvironmentObject cannot trigger view updates, @ObservedObject can.
D@ObservedObject shares data across unrelated views automatically.
Attempts:
2 left
💡 Hint
Consider how each property wrapper receives its data and how it is passed to views.
🔧 Debug
advanced
2:00remaining
Why does this view not update when the shared state changes?
Given this code, why does the Text not update when the button is tapped?
iOS Swift
class Score: ObservableObject {
  @Published var points = 0
}

struct ScoreView: View {
  var score = Score()
  var body: some View {
    VStack {
      Text("Points: \(score.points)")
      Button("Add Point") {
        score.points += 1
      }
    }
  }
}
ABecause the Button action is not called
BBecause @Published does not work with Int properties
CBecause 'score' is not marked with @StateObject or @ObservedObject, so changes don't trigger view updates
DBecause the Text view is outside the VStack
Attempts:
2 left
💡 Hint
Think about how SwiftUI detects changes in observable objects to update views.
❓ navigation
expert
3:00remaining
How to share @EnvironmentObject across multiple views in a navigation stack?
You want to share a UserSettings object using @EnvironmentObject across several views pushed in a NavigationStack. Which code snippet correctly injects the environment object so all views can access it?
A
NavigationStack {
  ContentView().environmentObject(UserSettings())
}
B
NavigationStack {
  ContentView()
}.environmentObject(UserSettings())
C
ContentView().environmentObject(UserSettings())
NavigationStack { ContentView() }
D
NavigationStack {
  ContentView()
}
UserSettings()
Attempts:
2 left
💡 Hint
The environment object must be injected at the root of the view hierarchy that contains the navigation stack.

Practice

(1/5)
1. What is the main purpose of using @EnvironmentObject in SwiftUI?
easy
A. To define the layout of a view using stacks.
B. To create a new view from scratch.
C. To handle user gestures like taps and swipes.
D. To share data easily across many views without passing it manually.

Solution

  1. Step 1: Understand the role of @EnvironmentObject

    @EnvironmentObject allows views to access shared data without passing it explicitly through every view initializer.
  2. Step 2: Compare with other options

    Options B, C, and D describe unrelated tasks like creating views, handling gestures, or layout, which are not the purpose of @EnvironmentObject.
  3. Final Answer:

    To share data easily across many views without passing it manually. -> Option D
  4. Quick Check:

    @EnvironmentObject shares data = A [OK]
Hint: Remember: @EnvironmentObject shares data across views [OK]
Common Mistakes:
  • Thinking @EnvironmentObject creates views
  • Confusing it with gesture handling
  • Assuming it controls layout
2. Which of the following is the correct way to declare an environment object in a SwiftUI view?
easy
A. @ObservedObject var model = MyModel()
B. @StateObject var model = MyModel()
C. @EnvironmentObject var model: MyModel
D. @Published var model: MyModel

Solution

  1. Step 1: Identify the correct property wrapper for environment objects

    @EnvironmentObject is used to declare a shared object injected from the environment, so the syntax is @EnvironmentObject var model: MyModel.
  2. Step 2: Understand other options

    @StateObject and @ObservedObject are for local ownership, and @Published is for properties inside ObservableObject classes, not for view declarations.
  3. Final Answer:

    @EnvironmentObject var model: MyModel -> Option C
  4. Quick Check:

    Declare environment object with @EnvironmentObject = A [OK]
Hint: Use @EnvironmentObject var name: Type to declare shared data [OK]
Common Mistakes:
  • Using @StateObject or @ObservedObject instead of @EnvironmentObject
  • Trying to use @Published in views
  • Forgetting the type annotation
3. Given the code below, what will be displayed when ContentView is shown?
class Counter: ObservableObject {
  @Published var count = 0
}

struct ContentView: View {
  @EnvironmentObject var counter: Counter
  var body: some View {
    Text("Count: \(counter.count)")
  }
}

// In the app entry point:
// ContentView().environmentObject(Counter())
medium
A. Runtime error due to missing environment object
B. Count: 0
C. Count: nil
D. Count: 1

Solution

  1. Step 1: Understand initial state of Counter

    The Counter class starts with count = 0, and this is published to views.
  2. Step 2: Check environment object injection

    The app injects Counter() into ContentView with .environmentObject(Counter()), so the view can access count.
  3. Final Answer:

    Count: 0 -> Option B
  4. Quick Check:

    Initial count is 0 and environment object is provided = D [OK]
Hint: Initial @Published values show as is when environment object is injected [OK]
Common Mistakes:
  • Assuming count starts at 1
  • Thinking environment object is missing
  • Confusing with optional values
4. What is the error in the following SwiftUI code using @EnvironmentObject?
class Settings: ObservableObject {
  @Published var isDarkMode = false
}

struct SettingsView: View {
  @EnvironmentObject var settings: Settings
  var body: some View {
    Toggle("Dark Mode", isOn: $settings.isDarkMode)
  }
}

// Usage:
// SettingsView()
medium
A. Missing .environmentObject(Settings()) when creating SettingsView
B. Toggle cannot bind to @Published properties
C. Settings class must be a struct, not a class
D. Toggle label must be a Text view, not a string

Solution

  1. Step 1: Identify environment object injection

    The code creates SettingsView() without injecting the Settings object using .environmentObject(Settings()). This causes a runtime crash.
  2. Step 2: Verify other parts

    Toggle can bind to @Published properties via $settings.isDarkMode, Settings can be a class, and Toggle accepts string labels.
  3. Final Answer:

    Missing .environmentObject(Settings()) when creating SettingsView -> Option A
  4. Quick Check:

    Always inject environment objects with .environmentObject() = B [OK]
Hint: Always add .environmentObject() when using @EnvironmentObject [OK]
Common Mistakes:
  • Forgetting to inject environment object
  • Thinking @Published can't bind to Toggle
  • Believing environment object must be a struct
5. You want to share a user profile object across multiple views using @EnvironmentObject. Which steps must you follow to correctly implement this shared state? A) Declare the profile class as ObservableObject with @Published properties. B) Create an instance of the profile and inject it using .environmentObject() at the app root. C) Use @EnvironmentObject in all views that need access to the profile. D) Pass the profile instance manually to each view initializer instead of using @EnvironmentObject.
hard
A. Only A, B, and C are needed.
B. Only B, C, and D are needed.
C. Only A and B are needed.
D. All A, B, C, and D are needed.

Solution

  1. Step 1: Identify correct steps for shared state

    The profile class must conform to ObservableObject with @Published properties (A). Then create and inject it at the app root with .environmentObject() (B). Views needing access use @EnvironmentObject (C).
  2. Step 2: Understand why D is incorrect

    Passing the profile manually (D) defeats the purpose of @EnvironmentObject, which avoids manual passing.
  3. Final Answer:

    Only A, B, and C are needed. -> Option A
  4. Quick Check:

    ObservableObject + inject + @EnvironmentObject = C [OK]
Hint: Inject once, declare ObservableObject, use @EnvironmentObject in views [OK]
Common Mistakes:
  • Passing environment object manually defeats its purpose
  • Forgetting to mark class ObservableObject
  • Not injecting at app root
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard