import ObservationBP
import SwiftUI
@Observable final class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
struct ContentView: View {
@Observing @State var person: Person = Person(name: "name", age: 1)
var body: some View {
VStack {
PersonNameView(person: person)
PersonAgeView(person: person)
}
}
}
private struct PersonNameView: View {
@Observing var person: Person
var body: some View {
Text(person.name)
.foregroundColor(Color(
red: .random(in: 0 ... 1),
green: .random(in: 0 ... 1),
blue: .random(in: 0 ... 1)
))
}
}
private struct PersonAgeView: View {
@Observing var person: Person
var body: some View {
Text("age \(person.age)")
.foregroundColor(Color(
red: .random(in: 0 ... 1),
green: .random(in: 0 ... 1),
blue: .random(in: 0 ... 1)
))
}
}
Swift Package Manager
ObservationView
.
ObservationView
either.@Observing
once in each View@State
and @StateObject
.Observation | ObservationBP |
---|---|
var person: Person | @Observing var person: Person |
@State var person = Person(name: "name", age: 1) | @Observing @State var person = Person(name: "name", age: 1) |