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()
import Foundation // Date
// todo item
struct TodoItem {
let date: Date
let item: String
}
// todo item samples
let todos = ["eat", "sleep", "play", "relax"]
let now = Date()
let nextyear = now.yearAfter
extension TodoItem {
static let samples = (1...5).map{ _ in
TodoItem(
date: .random(in: now...nextyear),
item: todos.randomElement()!
)
}
}
let todolist = TodoItem.samples
Sundell โฉ Sorting Swift collections โญ๏ธ
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]
enum Response {
case ok
case error(Int)
}
var responses: [Response] = [
.error(500), .ok, .ok, .error(404), .error(403)
]
// โญ๏ธ sort in place
responses.sort {
// Q: $0 is before $1 ?
switch ($0, $1) {
// error ordered by error code (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
}
}
Last updated