// โญ๏ธ 1. declare a type that conforms to `ObservableObject`classZoo:ObservableObject {// โญ๏ธ 2. declare published value(s) in this type@Publishedvar creatures = [Creature(name:"Gorilla", emoji:"๐ฆ"),Creature(name:"Peacock", emoji:"๐ฆ"), ]}// content viewstructContentView:View {// โญ๏ธ 3. declare & initialize a state object@StateObjectvar data =Zoo()var body: some View {// 4. access the state object's data in subviews }}
๐ ๅ่๏ผSwift Playgrounds (Keep Going with Apps) - Sharing Data Between Views.
๐ CreatureZoo
// โญ๏ธ 1. declare an observable object typeclassCreatureZoo:ObservableObject {// โญ๏ธ 2. declare published properties@Publishedvar creatures = [Creature(name:"Gorilla", emoji:"๐ฆ"),Creature(name:"Peacock", emoji:"๐ฆ"), ]}
๐ MyApp
@mainstructMyApp:App {// โญ๏ธ 3. intialize an observable object@StateObjectvar data =CreatureZoo()var body: some Scene {WindowGroup {ContentView()// โญ๏ธ 4. put data in environment .environmentObject(data) } }}
๐ ContentView
structContentView:View {// โญ๏ธ 5. inject data from environment@EnvironmentObjectvar data : CreatureZoovar body: some View {// โญ๏ธ 6. access data in subviews }}