Skip to content

Instantly share code, notes, and snippets.

@denis-obukhov
Last active March 11, 2024 06:15
Show Gist options
  • Save denis-obukhov/edbbe9cb2fe84520aa00d2f07cb5c4e5 to your computer and use it in GitHub Desktop.
Save denis-obukhov/edbbe9cb2fe84520aa00d2f07cb5c4e5 to your computer and use it in GitHub Desktop.
Leverage the power of Swift 5.9 brand new Parameter Packs to adopt the Equatable protocol for use in SwiftUI's .onChange(of:) based on changes to multiple parameters!
struct EquatablePack<each V: Equatable>: Equatable {
let value: (repeat each V)
init(_ value: repeat each V) {
self.value = (repeat each value)
}
static func == (lhs: Self, rhs: Self) -> Bool {
func throwIfNotEqual<T: Equatable>(_ lhs: T, _ rhs: T) throws {
guard lhs == rhs else { throw CancellationError() }
}
do {
repeat try throwIfNotEqual(each lhs.value, each rhs.value)
} catch {
return false
}
return true
}
}
/*
Usage example:
.onChange(of: EquatablePack(value1, value3, value3)) {
doSomething()
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment