Skip to content
DeveloperMemos

How to Sort a List of Strings Alphabetically in Swift

Swift, Sorting, Strings1 min read

Sorting a list of strings alphabetically is a common task in programming, and Swift, being a powerful programming language, provides multiple ways to sort lists. Here, we will discuss three of the most widely used methods to sort a list of strings in Swift.

Method 1: Using the "sorted" method

The simplest and most straightforward method to sort a list of strings in Swift is by using the "sorted" method. The "sorted" method sorts the elements in the list in ascending order by default and returns a new sorted list. Here's how you can use the "sorted" method to sort a list of strings:

1let names = ["John", "Jane", "Bob", "Alice"]
2let sortedNames = names.sorted()
3print(sortedNames)

Output:

1["Alice", "Bob", "Jane", "John"]

Method 2: Using the "sort" method

Another way to sort a list of strings in Swift is by using the "sort" method. Unlike the "sorted" method, the "sort" method sorts the elements in the list in place, meaning that the original list is modified. Here's how you can use the "sort" method to sort a list of strings:

1var names = ["John", "Jane", "Bob", "Alice"]
2names.sort()
3print(names)

Output:

1["Alice", "Bob", "Jane", "John"]

Method 3: Using the "sorted" method with a custom sorting closure

If you want to sort the list of strings in a custom order, you can use the "sorted" method along with a custom sorting closure. The sorting closure takes two elements and returns a Boolean value indicating whether the first element should appear before the second element in the sorted list. Here's how you can use the "sorted" method with a custom sorting closure to sort a list of strings:

1let names = ["John", "Jane", "Bob", "Alice"]
2let sortedNames = names.sorted { (name1, name2) -> Bool in
3 return name1 > name2
4}
5print(sortedNames)

Output:

1["John", "Jane", "Bob", "Alice"]

In the above example, the sorting closure compares the elements in reverse order, resulting in a sorted list in descending order.

In conclusion, sorting a list of strings in Swift is a straightforward task and can be done in multiple ways. Whether you want to sort the list in ascending or custom order, you can use the "sorted" or "sort" method along with a custom sorting closure to achieve your desired result.