Sort characters of a String in Swift


In this tutorial, you are going to learn how to sort characters of a String in Swift with examples.

In Swift, we are going to use the Swift sorted() method to sort a string by its characters in alphabetical order. It is possible to sort the string in ascending order as well as descending order using the sorted() method.

Sorting string characters in ascending order

Let’s first see an example below where we have sorted the string characters in ascending order:

var cityName = "chicago";

var stringStoredArr = cityName.sorted()

print(stringStoredArr)

Output:

["a", "c", "c", "g", "h", "i", "o"]

You can see that the sorted() method returned an array of characters from the string and order it alphabetically. In most cases, app developers need that returned array. But you may need it as a string instead of an array. In that case, you have to convert the array into a string.

So let’s see the code below, where we have sorted the string alphabetically and then return a string:

var cityName = "chicago";

var stringStoredArr = cityName.sorted()

var stringSorted = String( stringStoredArr )

print(stringSorted)

Output:

accghio

In the above code, we have used the String() method to convert the returned array into a string.

Sorting string characters in descending order

In order to sort the characters of a Swift string in descending order, we have to use sorted(by:) method. We just need to pass the argument to the sort() method.

Below is the program to sort a string in descending order by its characters:

var cityName = "chicago";

var stringStoredArr = cityName.sorted(by: >)

print(stringStoredArr)

Output:

["o", "i", "h", "g", "c", "c", "a"]

Just like the previous one, we can convert the returned array into a string using the Swift String() method:

var cityName = "chicago";

var stringStoredArr = cityName.sorted(by: >)

var stringSorted = String( stringStoredArr )

print(stringSorted)

Output:

oihgcca