I don't see where you've defined graphData, but for it to be observable it must be a class and have the ObservableObject protocol. Also, arrayInt and fooString must be properties of that class. You then need to instantiate the class and make a single copy of it available to all views. Assuming that you've created your project in a recent version of Xcode, here's an example:
import SwiftUI
@main
struct SwiftUIExampleApp: App { // the "main" App view created by Xcode
@StateObject var graphData = GraphData(). // makes a single copy of graphData available
var body: some Scene {
WindowGroup {
GraphView() // usually refers to ContentView()
.environmentObject(graphData). // passes a reference to the single copy of graphData down to GraphView
}
}
}
struct GraphView: View { // Your main view - View1
@EnvironmentObject var graphData : GraphData
var body: some View {
Text(graphData.fooString)
.padding()
// **** need to invoke DetailView somehow and pass it the reference to graphView i.e. .environmentObject(graphData) ****
}
}
struct DetailView: View {
@EnvironmentObject var graphData : GraphData
var body: some View {
Text("This is the detail view")
.onAppear{
graphData.appendToArray(foo: "OK", num: 21)
// can also directly address the vars
graphData.arrayInt.append(11)
graphData.fooString = "Yippee"
}
}
}
import Foundation
class GraphData : ObservableObject {. // this is your "data model"
//@Published var arrayInt = [6, 6.5] // arrayInt contains a real (6.5)
@Published var arrayInt = [6,7]
@Published var fooString = "Name"
func appendToArray(foo: String, num: Int) {
fooString = foo
arrayInt.append(num)
}
}
This should work, but I haven't fully checked - it's still early here in Oz!
Another approach to using GraphData, instead of @StateObject, is to make GraphData a singleton ( static let shared = GraphData() inside the class definition) then use @Published graphData = GraphData.shared
Regards, Michaela