Swift Sorting
Swift Sorting
Sort arrays with sorted() (returns new) or sort() (in-place). Provide a closure for custom order.
Sort
Sort ascending using sorted() and descending in-place using sort(by:).
Example
var nums = [3, 1, 2]
let ascending = nums.sorted()
print(ascending) // [1, 2, 3]
nums.sort(by: >)
print(nums) // [3, 2, 1]
This example sorts ascending using sorted() and descending in-place using sort(by:).
Case-Insensitive Sort
Provide a custom closure to sort strings without regard to case.
Example
let names = ["bob", "Alice", "dave"]
let caseInsensitive = names.sorted { $0.lowercased() < $1.lowercased() }
print(caseInsensitive) // ["Alice", "bob", "dave"]