I have a view (view1) to display different data, and I would like that view to change based on another variable.
struct View1: View {
let array = myFunc()
var body: some View {
VStack {
Text("\(settings.score)")
List {
ForEach(0..<array.count) { section in
NavigationLink(destination: RowDetailView(array: array[section])) {
RowView(array: array[section])
}
}
}
}
In another view I establish an Observable object:
class GameSettings: ObservableObject {
@Published var score = 1
}
That all works well elsewhere in other views. I can update it as needed.
I have a function to obtain the array variable, and I would like it to return a different array depending upon the current value of "score".
func myFunc() -> [arrayModel] {
@StateObject var settings = GameSettings()
if settings.score == 1 {
var array = [ arrayModel(example: example) ]
return array
}
else if settings.score == 2 {
var array = [ arrayModel(example: example) ]
return array
}
}
This doesn't seem to work. I have tried various tweaked versions of this, but can't find how to properly implement it. Any help would be greatly appreciated.
If the problem is that
settings.scoreisn't current inmyFunc, and ifmyFuncis in a SwiftUI view, you can do the following:@StateObject var settings = GameSettings()to@EnvironmentObject var settings: GameSettings, and move it outsidemyFunc.SceneDelegate, store a reference toGameSettings(), like this:static var gameSettings = GameSettings().SceneDelegate'sscene(_:willConnectTo:options:)function, supply theObservedObjectto your views by using the.environmentObjectmodifier, passing in the variable you stored in step #2, like this: