Skip to content

Instantly share code, notes, and snippets.

@maximkrouk
Last active June 3, 2020 15:24
Show Gist options
  • Save maximkrouk/9e7b4786a94edf474383d16ee2a4e26a to your computer and use it in GitHub Desktop.
Save maximkrouk/9e7b4786a94edf474383d16ee2a4e26a to your computer and use it in GitHub Desktop.
Identifiable wrapper for hashable values
@dynamicMemberLookup
@propertyWrapper
public struct IdentifiableBox<Content: Hashable>: Identifiable {
public var id: Int { content.hashValue }
public var content: Content
@inlinable
public var wrappedValue: Content {
get { content }
set { content = newValue }
}
@inlinable
public var projectedValue: Int { id }
@inlinable
public init(wrappedValue: Content) {
self.init(wrappedValue)
}
@inlinable
public init(_ content: Content) {
self.content = content
}
@inlinable
public subscript<T>(dynamicMember keyPath: KeyPath<Content, T>) -> T {
get { content[keyPath: keyPath] }
}
@inlinable
public subscript<T>(dynamicMember keyPath: WritableKeyPath<Content, T>) -> T {
get { content[keyPath: keyPath] }
set { content[keyPath: keyPath] = newValue }
}
}
@maximkrouk
Copy link
Author

maximkrouk commented May 29, 2020

Usage

struct Test<T: Identifiable> {
    var value: T
}

var array1: [IdentifiableBox<String>] = ["identifiable"]
var array2: [Test<IdentifiableBox<String>>] = [.init(value:"identifiable")]

array1.map(\.isEmpty) // [false]

See more:

Back to index

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment