Skip to content

Instantly share code, notes, and snippets.

@ollieatkinson
Created March 8, 2021 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ollieatkinson/4af4b51936b73aa12ab8de28bdd5b43a to your computer and use it in GitHub Desktop.
Save ollieatkinson/4af4b51936b73aa12ab8de28bdd5b43a to your computer and use it in GitHub Desktop.
Key value pairing with support for equality, hashing and coding
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