Home
Search
Sort String ArraysSort arrays with the sort method. Use funcs and closures to compare Strings and Ints.
Swift
This page was last reviewed on Dec 29, 2022.
Sort. In Swift we find many sorting approaches. Funcs can be used. An array of strings can be ordered alphabetically, or by any other property.
Array
With funcs, we can specify advanced comparison logic for sorting in Swift. And with closures, we add logic with inline function bodies.
Func example. To start, this program uses a func called "before" to compare 2 strings. We call sort() with the before func name as the argument.
And The animals array is sorted according to the logic in before. Strings are compared alphabetically.
Less than This operator is implemented for 2 strings. With it, "A" precedes "B."
True This is returned when the first argument comes before the second in sorted order.
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
Descending, Int array. To 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.
Tip The argument types in a 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
Strings by length. Here we sort a string array based on the results of a function call. We sort on the count of characters in each string.
Result The 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.characters.count < value2.characters.count } var values = ["yyy", "aa", "d", "gggg"] values.sort(by: length) // Display strings sorted by character count. print(values)
["d", "aa", "yyy", "gggg"]
Closure. 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 The in-keyword separates the return type from the return expression. So "Bool in" is used to return a Bool based on the comparison.
Arguments The arguments of a closure expression can be specified in the same way as in a 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"]
Syntax. 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.
Example 1 This closure (which sorts "values") omits the Int argument type of the elements in the array.
Example 2 This closure removes the "return" keyword. Typing "return" requires six key presses.
Example 3 The special variables $0 and $1 (and further) are available in closures. These are the first, second and further arguments.
Example 4 A single character can be used to sort. We specify the < operator. We can also use > for the opposite direction.
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 keys. A 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.
Here We sort the keys from our dictionary in alphabetical order. Then we loop over those keys and access the values.
// 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
A review. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 29, 2022 (edit).
Home
Changes
© 2007-2023 Sam Allen.