Skip to content

Instantly share code, notes, and snippets.

@sunshinejr
Last active September 20, 2021 09:47
Show Gist options
  • Save sunshinejr/09a06227974ae0d20f4a678132470920 to your computer and use it in GitHub Desktop.
Save sunshinejr/09a06227974ae0d20f4a678132470920 to your computer and use it in GitHub Desktop.
Swift Property wrapper for debouncing values
@propertyWrapper
public final class Debounced<T: Hashable>: BindingConvertible {
public let delay: Double
private var _value: T
private var timer: Timer? = nil
public var wrappedValue: T {
get {
return _value
}
set(newValue) {
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false, block: { [weak self] timer in
self?._value = newValue
timer.invalidate()
})
}
}
public var binding: Binding<T> {
return Binding(getValue: { return self.wrappedValue },
setValue: { newValue in self.wrappedValue = newValue })
}
public var wrapperValue: Binding<T> {
return self.binding
}
public init(wrappedValue: T, delay: Double) {
self._value = wrappedValue
self.delay = delay
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment