txagPman
txagPman

Reputation: 284

SwiftUI: How to use .presentation modifier for Alert? Getting a compiler type-check error

I am rebuilding a Quiz app I made in UIKit to SwiftUI for fun and I ran into a compiler error for the last .presentation modifier I have below.

I'm not sure how I would break this up. It seems simple enough. Running a 2012 MacBook Pro Retina i7.

@State var showingSaveAlert = false
@State var showingLoadSaveAlert = false


var loadProgress: Alert {
        Alert(title: Text("Load Progress?"), message: Text("Continue from question \(studySaver)?"), primaryButton: .default(Text("Load"), onTrigger: {
            self.loadProgressHandler()
        }), secondaryButton: .cancel())
    }

    var savedAlert: Alert {
        Alert(title: Text("Saved!"), message: Text("Your place has been saved. You may now leave this page without loosing progress."), dismissButton: .cancel())
    }


//MARK: SwiftUI
var body: some View {
        VStack{

        // Bunch of Swift UI Code within the VStack
        ...

            }
            .navigationBarTitle(Text(subject + " Test"), displayMode: .inline)
            .navigationBarItems(trailing:
                Button(action: {
                    self.showingSaveAlert = true
                    self.save()
                    print("Saved")
                }) {
                    Text("Save")
                    }
                    .presentation(showingSaveAlert ? savedAlert : nil)
            )
            .onAppear(){
                print("Test Page Appeared")
                self.showingLoadSaveAlert = true
                self.showingContinue = false
                self.questionLoader()
            }
            .presentation(showingLoadSaveAlert ? loadProgress : nil)


    } //MARK: End of SwiftUI

I would expect it to clear but I get a type-check error on the last modifier .presentation(showingLoadSaveAlert ? loadProgress : nil)

Error:
"The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions"

The main goal is to get an alert to show up when the View appears asking to load a save for a quiz.

Any thoughts?

Upvotes: 2

Views: 1028

Answers (1)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 120002

The issue is on this line: (And other alert presentation codes)

.presentation(showingSaveAlert ? savedAlert : nil)

Alerts should Bind to a Bool in SwiftUI.

change it to this:

.presentation($showingSaveAlert) { savedAlert }

Upvotes: 2

Related Questions