Skip to content

Instantly share code, notes, and snippets.

@yhkaplan
Created November 5, 2021 05:52
Show Gist options
  • Save yhkaplan/bffd6b3181d7e1d075a2b35c36dddd56 to your computer and use it in GitHub Desktop.
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
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