Sorting in Swift

Swift’s standard library provides sorting functionality for arrays and other collections. Let’s look at sorting for basic types first.

import Foundation

// Sorting functions work for any Comparable type
let strs = ["c", "a", "b"]
let sortedStrs = strs.sorted()
print("Strings:", sortedStrs)

// An example of sorting integers
var ints = [7, 2, 4]
ints.sort()
print("Ints:   ", ints)

// We can also check if an array is already in sorted order
let s = ints == ints.sorted()
print("Sorted: ", s)

To run the program, save it as sorting.swift and use swift command:

$ swift sorting.swift
Strings: ["a", "b", "c"]
Ints:    [2, 4, 7]
Sorted:  true

In Swift, we use the sorted() method to create a new sorted array, and the sort() method to sort an array in place. These methods are available for any collection whose elements conform to the Comparable protocol, which includes all of Swift’s standard numeric and string types.

The sorted() method returns a new array with its elements in sorted order, while sort() modifies the original array.

To check if an array is already sorted, we can compare it with its sorted version. This is not as efficient as Go’s IsSorted function, but it serves the same purpose for this example.

Swift’s standard library provides powerful and flexible sorting capabilities, including the ability to sort using custom comparators, which we’ll explore in future examples.