Skip to content

Instantly share code, notes, and snippets.

@carlynorama
Last active April 10, 2021 04:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlynorama/5682f604c50ceb9f5a29 to your computer and use it in GitHub Desktop.
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.
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)")
@Kaji01
Copy link

Kaji01 commented Oct 4, 2020

Thanks for sharing this! Coming from PHP, Swift's near-obstinate refusal to remember the order of arrays, lists, etc. is especially frustrating.

@shravanteegala
Copy link

shravanteegala commented Apr 10, 2021

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