carlynorama

the blog

Swiftly Sorting Dictionaries on Saturday

by Carlyn Maw on February 6, 2016, no comments

Laptop computer on kitchen counter with small pieces of paper lined up in a row.

Well this took way too long to figure out. I had a typo in a print statement that made it take even longer. Doh.

As it was hard won,  and involved sorting pieces of paper on our tiled kitchen counter to better understand the bubble sort, I thought I’d record the moment.

Fun discovery: an animated comparison of sorting algorithms.

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)")