Example 1: The difference between @ObservedObject and @EnvironmentObject.
Food.swift
import Foundation
class Food: ObservableObject {
@Published var type: String = "vegetable"
func changeType() {
let tmp = ["vegetable", "fruit", "meat", "dairy"]
let index = Int.random(in: 0..<tmp.count)
self.type = tmp[index]
}
}
ContentView.swift
import SwiftUI
struct ContentView: View {
@ObservedObject var food: Food = Food()
@EnvironmentObject var foodEn: Food
init() {
food.changeType()
}
var body: some View {
VStack {
Text("ObservedObject, \(food.type)")
.padding()
Text("EnvironmentObject, \(foodEn.type)")
.padding()
.onAppear{
foodEn.changeType()
}
Spacer()
Button(action: {
food.changeType()
foodEn.changeType()
}, label: {
Text("Change")
})
Spacer()
CompareView()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
CompareView.swift
import SwiftUI
struct CompareView: View {
@ObservedObject var food: Food = Food()
@EnvironmentObject var foodEn: Food
init() {
food.changeType()
}
var body: some View {
Text("CompareView-ObservedObject, \(food.type)")
.padding()
Text("CompareView-EnvironmentObject, \(foodEn.type)")
.padding()
.onAppear{
foodEn.changeType()
}
}
}
struct CompareView_Previews: PreviewProvider {
static var previews: some View {
CompareView()
}
}
App.swift
import SwiftUI
@main
struct ccApp: App {
let foodEn: Food = Food()
var body: some Scene {
WindowGroup {
ContentView().environmentObject(foodEn)
}
}
}