Menu
Coddy logo textTech

Environment Objects

Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 41 of 50.

Passing an object through every view down to the one that needs it gets tedious. Put it in the environment instead, and any view below can read it:

@StateObject private var cart = Cart()

var body: some View {
    NavigationStack {
        ShopView()
    }
    .environmentObject(cart)
}

A view further down declares what it needs with @EnvironmentObject, without an initial value:

struct CartBadge: View {
    @EnvironmentObject var cart: Cart

    var body: some View {
        Text("\(cart.count) in cart")
    }
}

ShopView never mentions the cart, but CartBadge inside it still gets the same object. If no view above provides it with .environmentObject, the app stops with an error when CartBadge is shown.

challenge icon

Challenge

Medium

CartBadge should show the shared cart's count. Provide cart to the VStack with .environmentObject, and change CartBadge to read it with @EnvironmentObject. The badge must read 1 in cart after one tap.

Try it yourself

import SwiftUI

@main
struct CoddyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction to SwiftUI

Practice on your own: Swift playground