Learn Courses My Dashboard

Passing variables downwards in SwiftUI?

I’m using the Calculator example in one of my apps for learning to code.
My app uses following code for a main view.

struct MainPanelView: View {
    @State var showingGame = false
    @State var showingSelection = false
    @State var showingCalculator = false
    @State var calcSelection = "Addition"
    let persistenceController = PersistenceController.shared
    var body: some View {
        if showingGame == true {
            MyGameView(showingGame: $showingGame, calcSelection: $calcSelection).environment(\.managedObjectContext, persistenceController.container.viewContext)
        else if showingSelection == true {
            SelectionView(showingSelection: $showingSelection, calcSelection:  $calcSelection).environment(\.managedObjectContext, persistenceController.container.viewContext)
        else if showingCalculator == true {
            CalcView(showingCalculator: $showingCalculator)
            MyMainView(showingGame: $showingGame, showingSelection: $showingSelection, showingCalculator: $showingCalculator)

struct MyMainView : View {
    @Binding var showingGame:Bool
    @Binding var showingSelection:Bool
    @Binding var showingCalculator:Bool
    var body: some View {
            Text("Willkommen").font(.system(size: 50))
            Button("Calculator Game"){
                showingGame = true
            Button("Calculator New") {
                showingCalculator = true
                showingSelection = true

The Calculator view is shown when the “Calculator New” button is pressed. I extended the number of rows in the calculator view and changed some of the lables. One is called “return” what it should do is to return to the main view. But since there are multiple layers of struct calls I cannot use @State @Binding to pass the variable showingCalculator to the calculator class where the buttonPressed function handles the pressed buttons.
How could this be solved without changing the base concept of my app ?

Kind Regards,


Never mind. Found it. Just passing the Stat variable along with the function call does the trick. Most probably not an elegant way. But works for now.


Yes you can pass state variables and in the child it’s a binding

You only need to do that if you’ll change the variable in the child, otherwise you can pass it as an input parameter