Skip to content

Commit 78f9d72

Browse files
authored
Add HashableObject protocol (pointfreeco#133)
SwiftUI's built-in navigation tools requires hashability and identifiability of objects, and while objects get identity for free, we must manually equate and hash objects by their object identity. Instead, the library can vend a protocol with default conformances.
1 parent a3aa5d4 commit 78f9d72

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

Sources/SwiftUINavigation/Documentation.docc/Articles/Navigation.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,3 +116,7 @@ Button {
116116

117117
- ``SwiftUI/View/navigationDestination(unwrapping:destination:)``
118118
- ``SwiftUI/NavigationLink/init(unwrapping:onNavigate:destination:label:)``
119+
120+
### Supporting types
121+
122+
- ``HashableObject``
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/// A protocol that adds a default implementation of `Hashable` to an object based off its object
2+
/// identity.
3+
///
4+
/// SwiftUI's navigation tools requires `Identifiable` and `Hashable` conformances throughout its
5+
/// APIs, for example `sheet(item:)` requires `Identifiable`, while `navigationDestination(item:)`
6+
/// and `NavigationLink.init(value:)` require `Hashable`. While `Identifiable` conformances come for
7+
/// free on objects based on object identity, there is no such mechanism for `Hashable`. This
8+
/// protocol addresses this shortcoming by providing default implementations of `==` and
9+
/// `hash(into:)`.
10+
public protocol HashableObject: AnyObject, Hashable {}
11+
12+
extension HashableObject {
13+
public static func == (lhs: Self, rhs: Self) -> Bool {
14+
lhs === rhs
15+
}
16+
17+
public func hash(into hasher: inout Hasher) {
18+
hasher.combine(ObjectIdentifier(self))
19+
}
20+
}

0 commit comments

Comments
 (0)