Swift - function to return different value based on another variable

204 views Asked by At

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.

1

There are 1 answers

1
West1 On

If the problem is that settings.score isn't current in myFunc, and if myFunc is in a SwiftUI view, you can do the following:

  1. Change @StateObject var settings = GameSettings() to @EnvironmentObject var settings: GameSettings, and move it outside myFunc.
  2. In your SceneDelegate, store a reference to GameSettings(), like this: static var gameSettings = GameSettings().
  3. In your SceneDelegate's scene(_:willConnectTo:options:) function, supply the ObservedObject to your views by using the .environmentObject modifier, passing in the variable you stored in step #2, like this:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        let contentView = ContentView()

        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView.environmentObject(SceneDelegate.gameSettings))
            self.window = window
            window.makeKeyAndVisible()
        }
    }