Sort array elements by length in Swift
This tutorial will show you how to sort an array of elements by a length in Swift. This type of sorting is done mainly on a string array to get a sorted array according to the element’s string length.
sort(by: ) function in Swift
sort(by: {element1, element2})
is the function in Swift that sorts the array elements in ascending order according to the specified sorting closure.
This function sorts the array in place means the original array is modified instead of creating a new sorted array.
The sorting closure takes two elements from the array and compares them to identify which element will come before the other and returns the boolean value accordingly.
Now using this function sort the string array elements in ascending or descending order according to their lengths.
string.count
: count method is used to find the length of the element, in this case, it’s a string. It counts the number of UTF-16 code units from a string or any specified element. The space in the string is also get counted.
Swift code to sort array elements by length
var arr = ["rohit", "john", "joe", "t", "harry", "rahul", "ab"] arr.sort(by: {$0.count < $1.count}) print(arr)
Output:
["t", "ab", "joe", "john", "rohit", "harry", "rahul"]
Also, refer to Find the largest value from an Array in Swift
Leave a Reply