SwiftUI: Presenting Errors in Alerts the Lazy (Generic) Way

Mark van Wijnen
CodeX
Published in
7 min readMay 24, 2024

--

Photo by Vitaly Gariev on Unsplash

Presenting errors in apps is essential to communicate failures to the end-users. A good error handeling should give the user the failure reason and a recovery suggestion. All of which is described in the LocalizedError protocol.

If you are building a production-ready app you should definitely take the time to figure out all the ways your app can fail and how you can gracefully inform this to the user and tell them what to do next. As so to avoid them not getting stuck in your app, clueless, having a bad user experience.

That being said. Error handeling can take a lot of time and sometimes we are just lazy and don’t care about the graceful part. If an error were to occur, just present it an alert and be done with it. Not the best user experience, but hey if you don’t care about that, it’s a quick and easy way to do it.

alert(isPresented:error:actions:message:)

SwiftUI already comes with a build-in solution: alert(isPresented:error:actions:message:). A view modifier that presents an alert with a message when an error is present. So before we dive into the generic part, let’s look at the code:

// Construct a type representing an error value that can be thrown.
enum SampleError: LocalizedError {
case anErrorOccured…

--

--

Mark van Wijnen
CodeX

macOS/iPadOS/iOS/watchOS/visionOS developer and SwiftUI enthousiast. “Stay Hungry, Stay Foolish!” — Steve Jobs