Sort
In Swift 5.8, we find many sorting approaches. Funcs can be used. An array of strings can be ordered alphabetically, or by any other property.
With funcs, we can specify advanced comparison logic for sorting in Swift. And with closures, we add logic with inline function bodies.
Func
exampleTo start, this program uses a func
called "before" to compare 2 strings. We call sort()
with the before func
name as the argument.
func before(value1: String, value2: String) -> Bool { // One string is alphabetically first. // ... True means value1 precedes value2. return value1 < value2; } var animals = ["walrus", "bird", "alligator", "zebra"] // Sort the array. animals.sort(by: before) // Display sorted array. for animal in animals { print(animal) }alligator bird walrus zebra
Int
arrayTo implement a descending sort, we use a "greater than" operator. Here we also change to an Int
array. We sort by the values of these integers.
func
(one that is used for sorting) must match the array element types.func descending(value1: Int, value2: Int) -> Bool { // A number precedes another if it is higher. // ... This is a descending sort. return value1 > value2; } var ids = [0, 10, 25, 100, 21, 22] ids.sort(by: descending) // Display results. for id in ids { print(id) }100 25 22 21 10 0
Here we sort a string
array based on the results of a function call. We sort on the count of characters in each string
.
string
array is sorted by length, from shortest (d) to longest (gggg).func length(value1: String, value2: String) -> Bool { // Compare character count of the strings. return value1.count < value2.count } var values = ["yyy", "aa", "d", "gggg"] values.sort(by: length) // Display strings sorted by character count. print(values)["d", "aa", "yyy", "gggg"]
A closure is an inline function block (and an environment with variables). In Swift we can pass a closure block to sort()
. No separate func
declaration is needed.
in
-keyword separates the return type from the return expression. So "Bool in" is used to return a Bool based on the comparison.func
.// An unordered string array. var values = ["DEF", "ABC", "XYZ", "GHI"] // Sort strings in descending alphabetical order. // ... Use closure for sort method. values.sort(by: { (value1: String, value2: String) -> Bool in return value1 > value2 }) print(values)["XYZ", "GHI", "DEF", "ABC"]
A closure can be specified with many syntax forms. Swift provides many reduced forms—these save us from typing characters. The short
forms may be easier to read.
Int
argument type of the elements in the array.var values = [10, 0, 20] // Sort with short closure syntax. values.sort(by: { v1, v2 in return v1 < v2 } ) print(values) var values2 = [40, 0, 80] // The return keyword is not required. values2.sort(by: { v1, v2 in v1 < v2 } ) print(values2) var values3 = [50, 0, 90] // The special variables $0 and $1 are used. // ... These indicate the first and second arguments. values3.sort(by: { $0 < $1 } ) print(values3) var values4 = [20, 0, 40] // We can use ascending and descending sorts with a single char. values4.sort(by: <) print(values4)[0, 10, 20] [0, 40, 80] [0, 50, 90] [0, 20, 40]
Sort
dictionary keysA dictionary's keys cannot be sorted in-place. A dictionary is unordered. But we can get the keys and convert this to an array and sort that.
// Create a dictionary. let animals = ["bird": 0, "zebra": 9, "ant": 1] // Get the array from the keys property. var copy = Array(animals.keys) // Sort from low to high (alphabetical order). copy.sort(by: <) // Loop over sorted keys. for key in copy { // Get value for this key. if let value = animals[key] { print("Key = \(key), Value = \(value)") } }Key = ant, Value = 1 Key = bird, Value = 0 Key = zebra, Value = 9
Sorting uses a func
that returns true or false. This func
tells us whether the first element comes before the second. With funcs and closures in Swift, we simplify custom sorts.