Putting aside the reasons why one might choose a value type over a reference type, does SwiftUI itself prefer use of @State vs @ObservedObject in terms of architecture.
Here for example are two implementations of a basic list app - cats implemented using a struct, dogs using a class:
import SwiftUI
struct Cat: Identifiable {
let id = UUID()
var name: String = "New cat"
}
final class Dog: Identifiable, ObservableObject {
let id = UUID()
@Published var name: String = "New dog"
}
final class Dogs: ObservableObject {
@Published var dogs: [Dog] = []
}
struct ContentView: View {
@State private var cats: [Cat] = []
@ObservedObject private var dogs = Dogs()
var body: some View {
VStack {
Text("Cats").bold()
ForEach($cats, content: CatView.init)
Button("New cat") {
cats.append(Cat())
}
Divider().padding()
Text("Dogs").bold()
ForEach(dogs.dogs, content: DogView.init)
Button("New dog") {
dogs.dogs.append(Dog())
}
}
}
}
struct CatView: View {
@Binding var cat: Cat
var body: some View {
TextField("Name", text: $cat.name)
}
}
struct DogView: View {
@ObservedObject var dog: Dog
var body: some View {
TextField("Name", text: $dog.name)
}
}
Very little difference in terms of coding...so:
Is there a reason why one might prefer one over the other? Apple's own examples often use structs +
@State+@Bindings.Is there any performance implication for either choice, say when either Cat or Dog object has many fields (ObservedObjects let you precisely specify which attribute should generate an
objectWillChangecall), or if the arrays hold many items, i.e. 100k's?When would one go for a reference type, when Bindings give pseudo-reference attributes to a value type?