sorting arrays

Sorting Arrays in Swift

Sorting arrays is a very common task. Swift has a built-in feature that is fast and easy to use. In this article you’ll learn all the details.

Hint: This post is using Swift 3

sort and sorted

Imagine we have an array of integers:

If the members of the array have a type that confirms to the Comparable protocol, then you can use the function sorted() to get an ordered array. Int does confirm to Comparable, so let’s do it:

So, that was very easy! Alternatively, we can also use the function sort(). In contrast to sorted(), it doesn’t return a new array but modifies the existing one. Of course this is only possible if the array is not a constant.

However, not all types confirm to the Comparable protocol.

Sorting arrays of dates

A good example for a type that doesn’t confirm to the Comparable protocol is Date. So if we want to sort an array of Date, then we can use

or

The only difference to the functions in the previous paragraph is, that we have to hand over a closure that has two array elements as parameters and returns a boolean. If the two elements are already in the right order, we have to return true. Sounds very straightforward. Let’s take a look at an example:

And indeed, the result is as expected:

sorting arrays

Performance

How is the performance? Is the build-in algorithm a good choice for sorting arrays? Yes, it is! As you can see in this article, a self implemented sort algorithm could be quicker in some situations, but generally speaking the performance is very good.

Differences between Swift 2 and Swift 3

It’s worth to mention that there’s a difference between Swift 2 and Swift 3. All the examples in this post are written in Swift 3. In Swift 2, the functions have different names.

  • Swift 2: sort() -> Swift 3: sorted()
  • Swift 2: sortInPlace()  -> Swift 3: sort()

For more details about the changed API naming, you can take a look at this Swift evolution proposal: Apply API Guidelines to the Standard Library.

Video

Check out this video as well:

References

Image: @ S.Pytel / shutterstock.com

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.

Amazon