swiftuiviewbuilder

Confused by SwiftUI ViewBuilder restrictions


I am learning SwiftUI and want to show a hint when the app launches for the first time. However, the code below is not building without the let _ = declarations, and I don't understand why:

var body: some View {
    if !UserDefaults.standard.bool(forKey: kIntroAppLaunchedInfoShown) {
        let _ = IntroManager.appLaunched()
        let _ = UserDefaults.standard.setValue(true, forKey: kIntroAppLaunchedInfoShown)
    }
    // …
}

I found an explanation that says:

view builders happen to support declarations, but not assignments

However, I am not sure why this is the case. It seems strange that I have to enter (in my case) useless code to get the code to build. Can anyone explain why this is necessary?


Solution

  • The comments to your question give a good explanation about why it is not working and the correct way to approach what you're trying to achieve.

    To help you a bit further, here is an example of how you could show the hint in the form of an alert. I've moved your launch code into the function appearing, which is called when the View is shown for the first time:

    struct ContentView: View {
    
        @State private var showingHint = false
    
        private func appearing() {
            if !UserDefaults.standard.bool(forKey: kIntroAppLaunchedInfoShown) {
                IntroManager.appLaunched()
                UserDefaults.standard.setValue(true, forKey: kIntroAppLaunchedInfoShown)
                showingHint = true
            }
        }
    
        var body: some View {
            VStack {
                Text("The body")
            }
            .onAppear(perform: appearing)
            .alert(
                "Hint",
                isPresented: $showingHint,
                actions: {}
            ) {
                Text("Welcome to my app")
            }
        }
    }