8

SwiftUI alerts and action sheets take Boolean bindings, but I want mine to display when a model property is nil. The model property is var servicePlayer: Player!, and I want an alert or action sheet to be presented when the tennis serving player is not yet selected (nil), but I'm not sure what would be a good way to approach this.

My model layer is composed of value type structs, so at the moment marking the property as @Published isn't an option. It doesn't sound worth it refactoring my whole model layer to a class reference type to be able to adopt Combine (I depend on the model instances being value type copies for undoing and redoing), but I may be wrong.

struct Match: Codable {
    ...
    var servicePlayer: Player!
    ...
}

.alert(isPresented: $isPresented) {
    Alert(title: Text("Who will serve?"),
              primaryButton: .default(Text("You")) {
                match.servicePlayer = .playerOne
            },
              secondaryButton: .default(Text("Opponent")) {
                match.servicePlayer = .playerTwo
            })
}

The $isPresented binding is just a placeholder. Since servicePlayer starts out nil, the idea is for the alert to be initially presented, but also reappear later in the tennis match when service player is nil again and yet to be selected.

2
  • 1
    It would be best if you showed some minimal code Commented Jan 29, 2021 at 2:56
  • @NewDev I just added the relevant parts of the code, thanks. Commented Jan 29, 2021 at 3:11

1 Answer 1

9

As you probably understand, the isPresented parameter of .alert requires a Binding<Bool>.

I assume Match is a @State property in your view:

struct ContentView: View {
   @State var match: Match

   var body: some View { ... }
}

which means that when that changes, the view will recompute. This means that your particular case you can use Binding.constant(bool):

.alert(isPresented: .constant(match.servicePlayer == nil)) {
   Alert(...)
}

because the Alert will modify the state by changing match.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm trying to understand how .constant(match.servicePlayer == nil) work in terms of the body being a function of the view's state. If the alert is dismissed using an OK button, and the value of match.servicePlayer is still nil, shouldn't that immediately present the alert again? I know currently it doesn't, but why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.