Last active
September 20, 2021 09:47
-
-
Save sunshinejr/09a06227974ae0d20f4a678132470920 to your computer and use it in GitHub Desktop.
Swift Property wrapper for debouncing values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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