(Xcode 12 / iOS 14) How can I resolve compatibility errors with calls to my App.Alert and SwiftUI.Alert?

Viewed 145

Inside ContentView I have the following code inside a view defined within var body: some View:

.alert(item: $alertItem) { (alert) -> Alert in
    Alert(
        title: Text(alert.title),
        message: Text(alert.message)
    )
}

The first two lines throw the following two compiler errors, respectively:

Declared closure result 'App.Alert' is incompatible with contextual type 'SwiftUI.Alert'
Extra arguments at positions #1, #2 in call

I have a struct defining AlertItem as follows:

struct AlertItem: Identifiable {    // *
  var id = UUID()
  var title: String
  var message: String
}

How can I resolve the compatibility errors, such that it conforms to SwiftUI.Alert? Any advice whatsoever would be much appreciated.

1 Answers

You can try the following:

.alert(item: $alertItem) { alert in
    SwiftUI.Alert(
        title: Text(alert.title),
        message: Text(alert.message)
    )
}
Related