Skip to content

Instantly share code, notes, and snippets.

@pilky
Created February 17, 2017 17:24
Show Gist options
  • Save pilky/c19ac202c06159b2a63446b3a94c3c7e to your computer and use it in GitHub Desktop.
Save pilky/c19ac202c06159b2a63446b3a94c3c7e to your computer and use it in GitHub Desktop.
Key value mapping for swift dictionaries
import UIKit
extension Dictionary {
init<S: Sequence>(_ pairs: S) where S.Iterator.Element == (Key, Value) {
self = [:]
for (k,v) in pairs { self[k] = v }
}
func keyValueMap<T: Hashable, S>(_ transform: (Key, Value) throws -> (T, S)) rethrows -> [T: S] {
var newDict = [T: S]()
for (k,v) in self {
let (newK, newV) = try transform(k, v)
newDict[newK] = newV
}
return newDict
}
func keyValueFlatMap<T: Hashable, S>(_ transform: (Key, Value) throws -> (T?, S?)) rethrows -> [T: S] {
var newDict = [T: S]()
for (k,v) in self {
let (optionalK, optionalV) = try transform(k, v)
guard let newK = optionalK, let newV = optionalV else { continue }
newDict[newK] = newV
}
return newDict
}
}
enum Keys: String {
case one
case two
case three
}
let dict = ["one": 1, "two": 2, "three": 3]
let dictToFlatten = ["one": 1, "two": 2, "three": 3, "four": 4]
let converted = Dictionary(dict.map { (k,v) in (Keys(rawValue: k)!, v)})
converted
let converted2 = dict.keyValueMap { k, v in (Keys(rawValue: k)!, v) }
converted2
let converted3 = dictToFlatten.keyValueFlatMap { k, v in (Keys(rawValue: k), v) }
converted3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment