2

I want to know how I can run some logic func or control flow operator before SwiftUI attempt to render ContentView? where and how I can put my codes?

Updated: init(){} before var body: some Scene

When I use init and do my logic there I cannot find a way to report my results of process, how I can solve this issue?

my code:

    import SwiftUI

@main
struct _99App: App
{
    init() {
        let firstName = "omid"
        print(firstName)
    }
    
    @State var name : String = firstName // ← Here        Error: Cannot find 'firstName' in scope
    
    
    var body: some Scene {

        WindowGroup {
            
            ContentView(name: $name)
                
        }
 
        
        
    }
}

PS: basically I need a place to run my logic before any thing happens in app.

1

1 Answer 1

2

You can use some kind of ObservableObject as StateObject which will be initialised before everything else.

So the solution might look like following

let globalState = MyAppState()

@main
struct _99App: App
{
    @StateObject var appState = globalState
    
    init() {
       globalState.firstName = "updated"
        print("updated")
    }

    var body: some Scene {
        WindowGroup {
            ContentView().environmentObject(appState)
            // and use as
            // @EnvironmentObject var appState: MyAppState
            // inside ContentView
        }
    }
}

class MyAppState: ObservableObject {
    @Published var firstName: String
    
    init() {
        self.firstName = "omid"
        print(firstName)
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

if you put this code init() { print("⌘") } *** before ***var body: some Scene you would see it runs faster than MyAppState-Class, run time of MyAppState is almost the same as ContentView, in the fact they are happing at the same time, like domino, but I want first position of code running in app! as you will see the sign of ⌘ would be printed always first and way faster than print(firstName) and I want get that place for my logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.