Created
November 5, 2021 05:52
-
-
Save yhkaplan/bffd6b3181d7e1d075a2b35c36dddd56 to your computer and use it in GitHub Desktop.
Convenient wrapper to make existing types conform to identifiable without changing their definition
This file contains 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
let a = IdentifiableItem(User(id: 1)) | |
let b = IdentifiableItem(User(id: 1), id: \.id) | |
@dynamicMemberLookup | |
struct IdentifiableItem<Item, ID: Hashable>: Identifiable { | |
var item: Item | |
let id: ID | |
init(_ item: Item) where ID == UUID { | |
self.item = item | |
self.id = UUID() | |
} | |
init(_ item: Item, id: KeyPath<Item, ID>) { | |
self.item = item | |
self.id = item[keyPath: id] | |
} | |
public subscript<Property>(dynamicMember keyPath: WritableKeyPath<Item, Property>) -> Property { | |
get { item[keyPath: keyPath] } | |
set { item[keyPath: keyPath] = newValue } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment