Last active
January 14, 2017 04:59
-
-
Save unledrob/aea8b29259eb6c213bed6056ca30d40d to your computer and use it in GitHub Desktop.
Using reduce to convert an array to a dictionary in Swift
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
| let playersArray: [[String: String]] = [ | |
| ["number": "1", "name": "De Gea", "position": "G"], | |
| ["number": "3", "name": "Bailly", "position": "D"], | |
| ["number": "6", "name": "Pogba", "position": "M"], | |
| ["number": "9", "name": "Ibrahimovic", "position": "F"], | |
| ["number": "8", "name": "Mata", "position": "M"], | |
| ["number": "10", "name": "Rooney", "position": "F"] | |
| ] | |
| let playersDictionary = playersArray.reduce([String:[String:String]](), { (dict, tuple) in | |
| guard let number = tuple["number"] else { return dict } | |
| var dict = dict | |
| dict[number] = tuple | |
| return dict | |
| }) | |
| // [ | |
| // "9": ["position": "F", "number": "9", "name": "Ibrahimovic"], | |
| // "1": ["position": "G", "number": "1", "name": "De Gea"], | |
| // "8": ["position": "M", "number": "8", "name": "Mata"], | |
| // "10": ["position": "F", "number": "10", "name": "Rooney"], | |
| // "6": ["position": "M", "number": "6", "name": "Pogba"], | |
| // "3": ["position": "D", "number": "3", "name": "Bailly"] | |
| // ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment