Last active
April 5, 2021 15:56
-
-
Save milanpanchal/ccc4994264ba74d3daf067a0a24c335d to your computer and use it in GitHub Desktop.
To group an array according to some criteria in Swift
This file contains 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
// https://medium.com/@milanpanchal24/how-to-group-array-using-dictionary-in-swift-6d185c8c79c | |
let fruits = ["Apple", "Apricot", "Avocado", | |
"Banana", "Boysenberry", "Blueberry", "Bing Cherry", | |
"Clementine", "Cucumber", | |
"Dates", "Dewberries", "Dragon Fruit"] | |
let groupedByAlphabet = Dictionary(grouping: fruits) { $0.first! } | |
print(groupedByAlphabet) | |
// Prints following output: | |
// ["B": ["Banana", "Boysenberry", "Blueberry", "Bing Cherry"], "A": ["Apple", "Apricot", "Avocado"], "D": ["Dates", "Dewberries", "Dragon Fruit"], "C": ["Clementine", "Cucumber"]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment