10

This error occurs with this code and I have no idea what it means:

.alert(isPresented: $showingAlert) {
                    Alert(title: Text(alertTitle), message: Text(alertMessage), dismissButton: .default(Text("OK")))

Any help please.

Thomas Vincent
  • 2,214
  • 4
  • 17
  • 25
Michael Mouer
  • 127
  • 1
  • 2
  • 8
  • 1
    Errors in SwiftUI usually don't show where they really are. Please, add code snippet of all the ContentView – Hrabovskyi Oleksandr Jan 05 '20 at 02:23
  • It is likely you didn't place the .alert in the correct place. You may have added it inside a button label closure for example instead of placing it as a modifier to a button or another view. Further code would be useful. – alionthego Aug 02 '21 at 04:39

2 Answers2

4

I had this error message because the brackets (the rounded ones) were not correctly paired. Your code works, these versions also work (using code that is not a "one liner" and Editor/Structure/Re-Indent also helps to see what might be wrong :-) ):

.alert(isPresented: $showAlert) {
    Alert(title: Text("Title"),
          message: Text("An alert"),
          primaryButton: .default(Text("OK"), action: {
          }),
          secondaryButton: .cancel(Text("Cancel"), action: {
          })
    )
}

or this:

.alert(isPresented: $showAlert) {
    Alert(title: Text("Title"),
          message: Text("An alert"),
          primaryButton: .default(Text("OK")) {
          },
          secondaryButton: .cancel(Text("Cancel"))
    )
}
t1ser
  • 1,574
  • 19
  • 18
3

I had this problem too and Xcode become messy. What I did to fix in in my end was:

First, create the alert in a computed property:

 var alert: Alert {
        Alert(title: Text("Oops"), message: Text("Error Message"), dismissButton: .default(Text("Dismiss")))
    }

Then use the alert property at the end of your superview:

@State var showAlert = false
 var body: some View {
     ZStack {
             ...
     }.alert(isPresented: $showAlert, content: { self.alert })
 }

I hope this solution works for you too.

Pitt
  • 54
  • 2