Skip to content

Instantly share code, notes, and snippets.

@YusukeHosonuma
Last active August 27, 2016 12:27
Show Gist options
  • Save YusukeHosonuma/9bce847d26a3342835190f43c6a9b0d8 to your computer and use it in GitHub Desktop.
Save YusukeHosonuma/9bce847d26a3342835190f43c6a9b0d8 to your computer and use it in GitHub Desktop.
Array reduce to Dictionary helper function
// Definition
extension Array {
func reduceDictionary<Key: Hashable, Value>(extractKeyValue: Element -> (Key, Value)) -> [Key: Value] {
return reduce([Key: Value]()) {
var dictionary = $0.0
let (key, value) = extractKeyValue($0.1)
dictionary[key] = value
return dictionary
}
}
}
// How to use
let xs = [
Dog(id: "001", name: "pochi"),
Dog(id: "002", name: "jhon"),
Dog(id: "003", name: "mike"),
]
xs.reduceDictionary{ ($0.id, $0.name) } // => ["001": "pochi", "002": "jhon", "003": "mike"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment