Unlock This Episode
Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.
So this is great, our alert can now be more dynamic based on what is happening in the view.
But there’s a few things that are not ideal about how we have modeled this problem.
First of all, holding both a boolean and an optional to represent an alert leaves us open to holding invalid states. For example, what if the boolean is
true yet the optional is
nil? That means we are trying to present the alert but don’t have any data to actually show. Or if the boolean is
false yet the optional is non-
nil. That means we have some data we want to put into an alert, but we aren’t showing an alert.
This improperly modeled domain will add more and more complexity into your view because you can never really trust the data. You’ll always worry about the invalid states creeping up, causing you to sprinkle little bits of logic to handle them, and you’ll have to do extra work to clean up the state so that it stays as correct as possible. In fact, right now we are never
nil-ing out the
itemToDelete field, and so if another part of our view checks if its
nil for some other part of the feature’s logic we run the risk of making decisions based on malformed data.
So, using the simple binding boolean API for alerts works great for alerts that are static, but it’s not the way to go for alerts that are dynamic. Luckily SwiftUI provides another version of the
.alert modifier, so let’s take a look at that.
The ability to break down applications into small domains that are understandable in isolation is a universal problem, and yet there is no default story for doing so in SwiftUI. We explore the problem space and solutions, in both vanilla SwiftUI and the Composable Architecture.