Home > Software design >  "Variable is used before initialized" when @Environment(\.dismiss) is used
"Variable is used before initialized" when @Environment(\.dismiss) is used

Time:06-28

I'm trying to have a very simple SwiftUI view hierarchy: parent and a child. The child should be able to dismiss itself with a tap of a button.

The following code works fine

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink {
                ChildView()
            } label: {
                Text("Go")
            }
        }
    }
}

struct ChildView: View {
    
    @Environment(\.dismiss) var dismiss
    
    var body: some View {
        Text("Hello, world!")
            .padding()
        Button(action: {
            dismiss()
        }, label: {
            Text("Dismiss")
        })
    }
}

However, when I try to add a simple state and init() to the ChildView, I'm hitting a compilation error

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink {
                ChildView(foo: 42)
            } label: {
                Text("Go")
            }
        }
    }
}

struct ChildView: View {
    
    @Environment(\.dismiss) var dismiss
    @State private var myInt: Int
    
    init(foo: Int) {
        self.myInt = foo // <--- ERROR IS HERE, "Variable 'self.myInt' used before being initialized"
    }
    
    var body: some View {
        Text("Hello, world!")
            .padding()
        Button(action: {
            dismiss()
        }, label: {
            Text("Dismiss")
        })
    }
}

This error is very puzzling. I tried different things and as far as I can tell, the problem is in the combination of init() and @Environment(\.dismiss) presents. But I really need to have them both for the real project.

Anybody knows what's the reason for the error or how to fix it?

Xcode version: 13.4.1

CodePudding user response:

A @State var has to be initialised differently:

self._myInt = State(initialValue: foo)
  • Related