Last active
April 10, 2021 04:31
-
-
Save carlynorama/5682f604c50ceb9f5a29 to your computer and use it in GitHub Desktop.
One line sorting of dictionaries Swift 2.1, both by key and by value examples.
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 myDictionary = [ | |
"20" : "banna", | |
"60" : "apple", | |
"30" : "cucumber", | |
"10" : "starfruit" | |
] | |
//assume that sort() kinda takes 2 arguments i.e. sort(dictionary element a, dictionary element b) | |
//woriking its way down the array (http://www.sorting-algorithms.com/bubble-sort) | |
//compare the 0th assumed parameter(a) with the 1st assumed parameter (b), using the key (0 after decimal) | |
// < acending, > decending, case sensitive | |
//rise repeat. | |
//changed to .sorted in swift 3 | |
let sortedByKeyDictionary = myDictionary.sort { $0.0 < $1.0 } | |
print("\(sortedByKeyDictionary)") | |
//compare the 0th (a) with the 1st (b), using the value (1 after decimal) | |
//rinse repeat. | |
//changed to .sorted in swift 3 | |
let sortedByValueDictionary = myDictionary.sort { $0.1 < $1.1 } | |
print("\(sortedByValueDictionary)") |
How i Sort this type of Dictionary keys
let myDictionary = [
"1" : "Anar",
"4": "HHHH",
"20" : "banna",
"60" : "apple",
"30" : "cucumber",
"10" : "starfruit"
]
let sortedByKeyDictionary = myDictionary.sorted(by: { $0.0 < $1.0 })
print("\(sortedByKeyDictionary)")
// O/P is: [(key: "1", value: "Anar"), (key: "10", value: "starfruit"), (key: "20", value: "banna"), (key: "30", value: "cucumber"), (key: "4", value: "HHHH"), (key: "60", value: "apple")]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing this! Coming from PHP, Swift's near-obstinate refusal to remember the order of arrays, lists, etc. is especially frustrating.