Created
March 8, 2021 09:16
-
-
Save ollieatkinson/4af4b51936b73aa12ab8de28bdd5b43a to your computer and use it in GitHub Desktop.
Key value pairing with support for equality, hashing and coding
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
extension Dictionary { | |
public typealias KeyValuePairs = [KeyValuePair<Key, Value>] | |
public var keyValuePairs: KeyValuePairs { map(KeyValuePair.init) } | |
} | |
extension Collection where Element: KeyValuePair_P { | |
public var dictionary: [Element.Key: Element.Value] { Dictionary(uniqueKeysWithValues: map(\.tuple)) } | |
} | |
public protocol KeyValuePair_P { | |
associatedtype Key: Hashable | |
associatedtype Value | |
var key: Key { get } | |
var value: Value { get } | |
} | |
extension KeyValuePair_P { | |
public var tuple: (Key, Value) { (key, value) } | |
} | |
public struct KeyValuePair<Key, Value>: KeyValuePair_P where Key: Hashable { | |
public let key: Key | |
public let value: Value | |
public init(key: Key, value: Value) { | |
(self.key, self.value) = (key, value) | |
} | |
} | |
extension KeyValuePair: Decodable where Key: Decodable, Value: Decodable {} | |
extension KeyValuePair: Encodable where Key: Encodable, Value: Encodable {} | |
extension KeyValuePair: Equatable where Key: Equatable, Value: Equatable {} | |
extension KeyValuePair: Hashable where Value: Hashable {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment