Skip to content

Instantly share code, notes, and snippets.

@NeverwinterMoon
Forked from Amzd/Binding+didSet.swift
Created December 19, 2019 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NeverwinterMoon/6827fc6f64c1468bf6a437f8f8b1f31a to your computer and use it in GitHub Desktop.
Save NeverwinterMoon/6827fc6f64c1468bf6a437f8f8b1f31a to your computer and use it in GitHub Desktop.
SwiftUI Binding wrappers for willSet and didSet
extension Binding {
/// Wrapper to listen to didSet of Binding
func didSet(_ didSet: @escaping ((newValue: Value, oldValue: Value)) -> Void) -> Binding<Value> {
return .init(get: { self.wrappedValue }, set: { newValue in
let oldValue = self.wrappedValue
self.wrappedValue = newValue
didSet((newValue, oldValue))
})
}
/// Wrapper to listen to willSet of Binding
func willSet(_ willSet: @escaping ((newValue: Value, oldValue: Value)) -> Void) -> Binding<Value> {
return .init(get: { self.wrappedValue }, set: { newValue in
willSet((newValue, self.wrappedValue))
self.wrappedValue = newValue
})
}
}
struct FilterView: View {
@Binding var filters: [String]
@Binding var selectedFilters: Set<String>
var body: some View {
List(filters, id: \.self, selection: $selectedFilters.didSet {
print("Selection changed from \($1) to \($0)")
}, rowContent: { filter in
Text(filter)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment