๐ŸšฅStateObject

SwiftUI โŸฉ Data Flow โŸฉ StateObject

๐Ÿ“— ๅƒ่€ƒ๏ผšSwift Playgrounds (Keep Going with Apps) - Sharing Data Between Views.

๐Ÿ“ CreatureZoo

// โญ๏ธ 1. declare @ObservableObject
class CreatureZoo : ObservableObject {
    // โญ๏ธ 2. source of truth (@Published properties)
    @Published var creatures = [
        Creature(name: "Gorilla", emoji: "๐Ÿฆ"),
        Creature(name: "Peacock", emoji: "๐Ÿฆš"),
    ]
}

๐Ÿ“ MyApp

@main
struct MyApp: App {
    
    // โญ๏ธ 3. create data in app
    @StateObject var data = CreatureZoo()
    
    var body: some Scene {
        SPCAssessableWindowGroup(app: self, assessmentCandidates: [CreatureZoo()]) {
            NavigationView { 
                ContentView()
                    .navigationTitle("My Creatures")
            }
            // โญ๏ธ 4. put data in environment
            .environmentObject(data)
        }
    }
}

๐Ÿ“ ContentView

struct ContentView: View {
    
    // โญ๏ธ 5. inject data from environment
    @EnvironmentObject var data : CreatureZoo

    var body: some View {
        SPCAssessableGroup(view: self) {
            List {
                Text("ContentView")
                
                Section("Dance") {
                    NavigationLink("Make the Creatures Dance") { 
                        DancingCreatures()
                            .navigationTitle("Dancing Creatures")
                    }
                }
                
                // โญ๏ธ 6. use data
                ForEach(data.creatures) { creature in 
                    // ...
                }    
            }
        }
    }
}

Last updated