Last active
March 11, 2024 06:15
-
-
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!
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
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