#05: Sorting Array and Dictionaries in Swift

Sorting collections in Swift is straightforward thanks to the sorted(by:) function available in every object implementing Collection or Sequence.

This function can sort, using insertion sort, any sequence of elements that conforms to the Comparable protocol and when no optional sorting function is provided, elements are sorted in ascending order.


Let’s define an array of fruits:

var fruits = ["orange","apple","melon","lemon","coconut","miracle fruit"]

It can be easily sorted this way, we’ll obtain a new array containing the sorted elements:

fruits.sorted() // Will print ["apple", "coconut", "lemon", "melon", "miracle fruit", "orange"]

To reverse the default sorting order we can pass the greater-than > operator and our sequence will be ordered in the opposite direction:

fruits.sorted(by:>) // Will print ["orange", "miracle fruit", "melon", "lemon", "coconut", "apple"]

Obviously we can pass our custom compare function to order the sequence by different criteria, like for example ordering the fruits only considering their name’s lenght:

    $0.characters.count > $1.characters.count
// Will print ["miracle fruit", "coconut", "orange", "apple", "melon", "lemon"]


Dictionaries conform to Collection and everything we did above applies also to this data structure, let’s try this with a dictionary containing a list of recipes and their ingredients.

var recipes = [
            "Lasagna" : ["Meat and tomato sauce","Lasagna pasta","Bechamel Sauce","Nutmeg","Parmigiano"],
            "Vegetable Dumpling" : ["Dumpling dough","Vegetable filling"],
            "Pizza" : ["Pizza dough","Tomato sauce","Olive oil","Mozzarella","Basil"],
            "Curry Laksa" : ["Vegetable oil","Chicken stock","Chicken thighs","King prawns","Coconut milk","Fish balls"," Beansprouts","Thin rice noodles","Laska spicy paste"]

In the next snippet we will order the recipes by their name, with an ascending order:

    (e1:(String,[String]), e2:(String,[String])) -> Bool in
    e1.0 < e2.0

And now, let’s try something different ordering the recipes from the one with most ingredients to the one with less:

    $0.value.count > $1.value.count

To sort sequences with custom objects, your objects just need to conform to the Comparable protocol implementing five compare methods: <,>,==,<=,>= , each one returns a boolean with the result of the comparison.

Did you like this article? Let me know on Twitter or subscribe for updates!

I'm also on Twitter and GitHub.

Subscribe via RSS or email.