Create a computed @State variable in SwiftUI
Here is an approach I prefer with computed property & binding "on-the-fly"
private var bindableIsVisibleError: Binding<Bool> { Binding (
get: { self.model.usernameResult.isVisibleError },
set: { if !$0 { self.model.dismissUsernameResultError() } }
)
}
and usage (as specified)
Toggle(isOn: bindableIsVisibleError, label: { EmptyView() })
One solution is to use a Binding directly, which allows you to specify an explicit getter and setter:
func bindableIsVisibleError() -> Binding<Bool> {
return Binding(
get: { return self.model.usernameResult.isVisibleError },
set: { if !$0 { self.model.dismissUsernameResultError() } })
}
You would then use it like so:
Toggle(isOn: bindableIsVisibleError(), label: { EmptyView() })
Although this works, it doesn't look as clean as using a computed property, and I'm not sure what the best way to create the Binding is? (I.e. using a function as in the example, using a get-only variable, or something else.)