seq.sorted()

// seq.sorted()
func sorted() -> [Self.Element]
  where Self.Element: Comparable
// โญ๏ธ sort `Comparable` elements in ascending order (default).
let numbers: [Int] = [3, 2, 4, 1]
let sortedNumbers = numbers.sorted()

// โญ๏ธ in descending order.
numbers.sorted(by: >)

// โญ๏ธ make custom type conform to `Comparable`
extension TodoItem: Comparable {
    static func < (a: TodoItem, b: TodoItem) -> Bool {
        a.date < b.date
    }
}

todolist.sorted()

Examples

// custom type
enum Response {
    case ok
    case error(Int)
}

// โญ๏ธ make custom type conform to `Comparable`
extension Response: Comparable {
    // Q: a is before b ?
    static func < (a: Response, b: Response) -> Bool {
        switch (a, b) {
            
            // errors ordered by error codes (increasing)
            case let (.error(m), .error(n)): return m < n

            // successes are equivalent, none is before any other
            case (.ok, .ok): return false

            // error is before success
            case (.error, .ok): return true
            case (.ok, .error): return false
        }
    }
}

let responses: [Response] = [
    .error(500), .ok, .ok, .error(404), .error(403)
]

responses.sorted()
// [.error(403), .error(404), .error(500), .ok, .ok]

Last updated