Skip to content

Instantly share code, notes, and snippets.

@shaps80
Created September 11, 2024 15:29
Show Gist options
  • Save shaps80/5615c8a71fe26d229bf063d2e7c87a5c to your computer and use it in GitHub Desktop.
Save shaps80/5615c8a71fe26d229bf063d2e7c87a5c to your computer and use it in GitHub Desktop.
Simplifies binding option set values to a SwiftUI View.
import SwiftUI
public extension Binding where Value: OptionSet {
func toggling(_ value: Value.Element) -> Binding<Bool> {
.init(
get: {
wrappedValue.contains(value)
},
set: {
if $0 {
wrappedValue.insert(value)
} else {
wrappedValue.remove(value)
}
}
)
}
}
@shaps80
Copy link
Author

shaps80 commented Sep 11, 2024

Example:

struct ContentView: View {
    @State private var edges: Edge.Set = []
    
    var body: some View {
        Toggle("", isOn: $edges.toggling(.bottom))
    }
}

Toggling the control, will insert/remove the .bottom value from the option set. Can be used with any OptionSet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment