Sort an array of strings alphabetically in Swift


Previously I published a tutorial on sorting an array in Swift where you can find examples of sorting arrays of integers. Now in this tutorial, you are going to learn how to sort an array of strings alphabetically.

To sort a string type array in alphabetical order, we can use the in-build Swift sort() and sorted() method. Let’s see some examples of sorting an array of strings in both ascending and descending order.

The sort() method changes the original array, whereas the sorted() method keeps the original array unchanged and returns a new array.

To perform our task, consider an array that contains some name of cities:

var cities = ["Bruges", "Liverpool", "Zadar", "Atlanta", "Malaga", "Knoxville"]

Our task is to sort the name of the cities in alphabetical order with ascending and descending order.

Sorting array in ascending order

Below is the example of sorting a Swift array in ascending order using the sort() method:

var cities = ["Bruges", "Liverpool", "Zadar", "Atlanta", "Malaga", "Knoxville"]

cities.sort()

print(cities)

Output:

["Atlanta", "Bruges", "Knoxville", "Liverpool", "Malaga", "Zadar"]

Now see another example of doing the same thing with sorted() method:

let cities = ["Bruges", "Liverpool", "Zadar", "Atlanta", "Malaga", "Knoxville"]

let sortedCities = cities.sorted()

print(sortedCities)

This time, our program has created a new array with the elements sorted in ascending order.

Sorting array in descending order

Now let’s see an example of sorting an array of string type in alphabetically descending order:

var cities = ["Bruges", "Liverpool", "Zadar", "Atlanta", "Malaga", "Knoxville"]

cities.sort(by: >)

print(cities)

Output:

["Zadar", "Malaga", "Liverpool", "Knoxville", "Bruges", "Atlanta"]

In the above example, our original array has been modified.

We can use the sorted(by:) method to create a new array and at the same time keep the original array unchanged. Below is the example:

let cities = ["Bruges", "Liverpool", "Zadar", "Atlanta", "Malaga", "Knoxville"]

let sortedCities = cities.sorted(by: >)

print(sortedCities)