Last active
August 27, 2016 12:27
-
-
Save YusukeHosonuma/9bce847d26a3342835190f43c6a9b0d8 to your computer and use it in GitHub Desktop.
Array reduce to Dictionary helper function
This file contains hidden or 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
| // 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