Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)")
@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