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.samplesSundell ⟩ Sorting Swift collections ⭐️
Examples
Last updated
Was this helpful?