In my Swift project, the data and the front-end buttons to trigger changes in the data are separated by several layers of objects. How do I make the front-end views reflect changes made several layers removed? I imagine that this is a fairly common situation in Swift development.
Here is a working example, with no separating layers between the view and the data.
import Foundation
import SwiftUI
import OrderedCollections
class Test: ObservableObject {
@Published var array: [String] = []
var num: Int = 0
func add() {
array.append(String(num))
num += 1
}
}
struct testView: View {
@ObservedObject var test = Test()
var body: some View {
VStack {
Button(action: { test.add() }) {
Text("Add Item to Array")
}
Text("")
Text("Items")
Text(Array(test.array).description)
}
}
}
@main
struct app: App {
var body: some Scene {
WindowGroup {
testView()
}
}
}
Here is an example with a "Middle" class that doesn't work.
class Test: ObservableObject {
@Published var array: [String] = []
var num: Int = 0
func add() {
array.append(String(num))
num += 1
}
}
class Middle: ObservableObject {
@ObservedObject var test: Test = Test()
}
struct testView: View {
@ObservedObject var m = Middle()
var body: some View {
VStack {
Button(action: { m.test.add() }) {
Text("Add Item to Array")
}
Text("")
Text("Items")
Text(Array(m.test.array).description)
}
}
}
@main
struct app: App {
var body: some Scene {
WindowGroup {
testView()
}
}
}
Note: with other code, I seemingly have been able to get my views to update changing data far removed from the front-end. I am sure it is possible--what I am looking for is the systematic way to make this work (my current method is just adding @ObservableObject, @Published, and @ObservedObject to everything the data touches until it works--or doesn't).