Last active
August 26, 2024 13:53
-
-
Save Iron-Ham/d0eb72822f0965a3688241a70ec08f8c to your computer and use it in GitHub Desktop.
Use property wrappers to ignore a variable for synthesized `Equatable` and `Hashable`.
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
import Foundation | |
@propertyWrapper | |
struct IgnoreEquatable<Wrapped>: Equatable { | |
var wrappedValue: Wrapped | |
static func == (lhs: IgnoreEquatable<Wrapped>, rhs: IgnoreEquatable<Wrapped>) -> Bool { | |
true | |
} | |
} | |
@propertyWrapper | |
struct IgnoreHashable<Wrapped>: Hashable { | |
@IgnoreEquatable var wrappedValue: Wrapped | |
func hash(into hasher: inout Hasher) {} | |
} | |
// Usage | |
// You can use this to ignore variables and allow for synthesized `Hashable` and `Equatable` declarations. | |
// Example: | |
// Before | |
struct SomeStruct: Equatable, Hashable { | |
let count: Int | |
let action: () -> Void | |
static func == (lhs: SomeStruct, rhs: SomeStruct) -> Bool { | |
return lhs.count == rhs.count // doesn't update automatically as we change and update the struct | |
} | |
func hash(into hasher: inout Hasher) { | |
hasher.combine(count) | |
} | |
} | |
// After | |
// This equality and hashable declaration is generated, and so will update as the struct changes. | |
struct SomeStruct2: Equatable, Hashable { | |
let count: Int | |
@IgnoreHashable var action: () -> Void | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that
Hashable
requiresEquatable
, so in order to ignore a variable for bothEquatable
andHashable
, all you need is the@NotHashable
property wrapper. ❤️