I have a "yes/no" confirmation alert I want to show to a user. If they say yes, we proceed with an action, otherwise we don't. But I'd like to have an "expert" mode where the user isn't prompted and we just proceed with the action.
The question is, how do I avoid having to write the code that runs the action (even if it is as single function call) at two different code sites? I.e.
HStack { .... }.alert(isPresented: $showConfirm) {
Alert(title: Text("Do Something"),
primaryButton: .default(Text("Yes"), { runMyCode() }),
secondaryButton: .cancel())
}
will suffice to show the alert. But at the point where I might set showConfirm, I must do this:
if (self.expertMode) {
runMyCode()
}
else {
self.showConfirm = true
}
So now I've listed runMyCode()
twice, which I really want to avoid.
What I'd really like to be able to do is write something like this:
}.askYesNo(isPresented: $self.showConfirm,
autoConfirmWhen: $self.expertMode, action: { runMyCode() })
which would take care of assembling the alert for me, but only if expertMode was false. Otherwise, it wouldn't bother, and it just run the specified action. If it did assemble the alert, the action parameter would be run if the user presses "Yes".
As an alternate question if nobody can figure that out, how could i do something like
isPresented: $self.showConfirm && !$self.expertMode
I.e. given two boolean variables, I want to pass in a binding which is the boolean and of their values. Can't figure out how to make a new one.
Yes, I can do all this by writing the logic out for all of it explicitly, to make it happen. The point is to find a simple pattern that avoids code replication and is as easy as a oneline modifier (askYesNo()) that encapsulates all the info (text, action, condition for running or not showing) at one call point.