Swift example

How to sort an array of objects by property in Swift

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Pass a closure that compares the property: people.sorted { $0.age < $1.age } returns a new sorted array, and people.sort { $0.age < $1.age } sorts a var in place. Use > for descending order, and compare tuples to sort by several properties: ($0.last, $0.first) < ($1.last, $1.first).

An array of your own structs or classes has no natural order, so sorted() with no arguments won't compile. You tell Swift how to order two elements, most often with a closure that compares one property, and the standard library does the rest. The sections below cover sorted(by:) and sort(by:), descending order, sorting by several properties, strings that should ignore case or read numbers as numbers, optional properties, key paths and Foundation's KeyPathComparator, and making a type Comparable, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1sorted(by:) and sort(by:)Recommended

sorted(by:) takes a closure that answers one question: should the first element come before the second? Return $0.age < $1.age for ascending order and $0.age > $1.age for descending. It returns a new array and leaves the original alone, so it works on a let. sort(by:) takes the same closure but reorders the array in place, so the array must be a var. Neither needs an import.

sorted_by.swift
struct Person {
    let name: String
    let age: Int
}

let people = [
    Person(name: "Maya", age: 34),
    Person(name: "Leo", age: 27),
    Person(name: "Ines", age: 41),
    Person(name: "Omar", age: 19),
]

// sorted(by:) returns a new array; people is unchanged
let byAge = people.sorted { $0.age < $1.age }
for p in byAge {
    print(p.name, p.age)
}

// Flip the comparison for descending order
let oldestFirst = people.sorted { $0.age > $1.age }
print(oldestFirst.map(\.name))

// The same closure works on any property
print(people.sorted { $0.name < $1.name }.map(\.name))

// sort(by:) sorts a var in place and returns nothing
var team = people
team.sort { $0.age < $1.age }
print(team.map(\.age))
print(people.map(\.age))

Output

sorted lists Omar (19) first and Ines (41) last. Flipping the operator gives ["Ines", "Maya", "Leo", "Omar"], and comparing name sorts alphabetically. After team.sort, team holds [19, 27, 34, 41] while people still prints [34, 27, 41, 19]: arrays are values, so sorting the copy leaves the original as it was. Calling sort on a let array doesn't compile: cannot use mutating member on immutable value: 'ages' is a 'let' constant.

2Sort by several properties

To break ties with a second property, compare tuples. Swift compares tuples of Comparable values element by element, so ($0.last, $0.first) < ($1.last, $1.first) sorts by last name and falls back to the first name only when the last names match. That works when every key goes the same direction. For mixed directions, compare the first key and return early when it differs. The standard library documents sort and sorted as stable, so elements that compare equal keep their order.

multiple.swift
struct Employee {
    let last: String
    let first: String
    let dept: String
    let salary: Int
}

let staff = [
    Employee(last: "Silva", first: "Rita", dept: "Ops", salary: 72_000),
    Employee(last: "Khan", first: "Omar", dept: "Dev", salary: 95_000),
    Employee(last: "Silva", first: "Ana", dept: "Dev", salary: 88_000),
    Employee(last: "Khan", first: "Aisha", dept: "Ops", salary: 72_000),
]

// Tuples compare element by element: last name, then first name
let byName = staff.sorted { ($0.last, $0.first) < ($1.last, $1.first) }
print(byName.map { "\($0.first) \($0.last)" })

// Mixed directions: dept ascending, salary descending
let byDept = staff.sorted {
    if $0.dept != $1.dept {
        return $0.dept < $1.dept
    }
    return $0.salary > $1.salary
}
for e in byDept {
    print(e.dept, e.salary, e.first)
}

// The sort is stable: equal salaries keep their earlier order
let alphabetical = staff.sorted { $0.first < $1.first }
let bySalary = alphabetical.sorted { $0.salary < $1.salary }
print(bySalary.map { "\($0.first) \($0.salary)" })

Output

The tuple sort puts both Khans first, Aisha before Omar, then Ana and Rita Silva. In the mixed sort, Dev comes before Ops and each department lists the higher salary first; Rita and Aisha both earn 72000, so they stay in their input order (Rita first). The last line shows the stable sort at work: sorting by first name and then by salary leaves Aisha 72000 ahead of Rita 72000, so the earlier order survives as the tiebreaker.

3Case-insensitive and natural string order

Comparing String properties with < compares Unicode values: every uppercase A to Z comes before every lowercase a to z, digits compare one at a time so item10 lands before item9, and accented letters go after z. For names and file names people read, use Foundation's localizedStandardCompare(_:), the order Finder uses: it ignores case and reads runs of digits as numbers. It returns a ComparisonResult, so check it against .orderedAscending. It follows the user's locale; to pin one, call compare(_:options:range:locale:) with the options you want.

strings.swift
import Foundation

struct File {
    let name: String
}

let files = [
    File(name: "item10.txt"),
    File(name: "Item2.txt"),
    File(name: "item9.txt"),
    File(name: "item1.txt"),
]

// Plain < compares Unicode scalars: "I" < "i" and "1" < "9"
print(files.sorted { $0.name < $1.name }.map(\.name))

// Case-insensitive, but digits still compare one by one
print(files.sorted { $0.name.lowercased() < $1.name.lowercased() }.map(\.name))

// Finder-style order: ignores case and reads numbers as numbers
let natural = files.sorted {
    $0.name.localizedStandardCompare($1.name) == .orderedAscending
}
print(natural.map(\.name))

// Accented letters: < puts them after z
let names = ["Zoe", "Émile", "adam", "Eve"]
print(names.sorted())
print(names.sorted { $0.localizedStandardCompare($1) == .orderedAscending })

// The same idea with a fixed locale instead of the user's
let enUS = Locale(identifier: "en_US")
let fixed = names.sorted {
    $0.compare($1, options: [.caseInsensitive, .numeric], locale: enUS)
        == .orderedAscending
}
print(fixed)

Output

Plain < puts Item2.txt first because I sorts before i, and item10.txt before item9.txt. lowercased() fixes the case but not the numbers. localizedStandardCompare gives the order people expect: item1.txt, Item2.txt, item9.txt, item10.txt. For the names, sorted() prints ["Eve", "Zoe", "adam", "Émile"] and both locale-aware versions print ["adam", "Émile", "Eve", "Zoe"]. The .numeric option is what makes 10 sort after 9.

4Optional properties: nil last

Optional isn't Comparable, so $0.due < $1.due on an Int? property fails with value of optional type 'Int?' must be unwrapped to a value of type 'Int'. You have to decide where nil goes. A switch over both values spells the rule out. For a number, a shorter trick is to replace nil with the largest value with ??, which sends it to the end; .min sends it to the front.

optionals.swift
struct Todo {
    let title: String
    let due: Int?
}

let todos = [
    Todo(title: "Deploy", due: 12),
    Todo(title: "Docs", due: nil),
    Todo(title: "Review", due: 3),
    Todo(title: "Refactor", due: nil),
    Todo(title: "Tests", due: 7),
]

// Optionals are not Comparable, so decide where nil goes yourself
let nilLast = todos.sorted { a, b in
    switch (a.due, b.due) {
    case let (x?, y?): return x < y
    case (_?, nil): return true
    case (nil, _): return false
    }
}
print(nilLast.map { "\($0.title) \($0.due.map(String.init) ?? "-")" })

// Shorter: treat nil as the largest possible value
let viaDefault = todos.sorted { ($0.due ?? .max) < ($1.due ?? .max) }
print(viaDefault.map(\.title))

// nil first instead
let nilFirst = todos.sorted { ($0.due ?? .min) < ($1.due ?? .min) }
print(nilFirst.map(\.title))

Output

The switch sorts the dated items by day (Review 3, Tests 7, Deploy 12) and puts Docs and Refactor last, in their original order. ?? .max gives the same result in one line. With ?? .min the two undated items move to the front. The default trick treats nil as equal to a real Int.max; if that value can occur, use the switch.

5Key paths and KeyPathComparator

If you sort by many different properties, a key path names the property once instead of twice. A short extension on Sequence reads the property through $0[keyPath: keyPath] and needs no import. Foundation also ships KeyPathComparator and sorted(using:), which take one comparator or an array of them, each with its own order. On Apple platforms they need iOS 15 or macOS 12; they run here on Linux.

key_paths.swift
import Foundation

struct Product {
    let name: String
    let price: Double
    let stock: Int
}

let products = [
    Product(name: "Lamp", price: 39.5, stock: 4),
    Product(name: "Desk", price: 210.0, stock: 2),
    Product(name: "Chair", price: 89.0, stock: 4),
]

// A small helper: sort by any Comparable property, named by key path
extension Sequence {
    func sorted<T: Comparable>(
        by keyPath: KeyPath<Element, T>,
        ascending: Bool = true
    ) -> [Element] {
        sorted {
            ascending ? $0[keyPath: keyPath] < $1[keyPath: keyPath]
                      : $0[keyPath: keyPath] > $1[keyPath: keyPath]
        }
    }
}

print(products.sorted(by: \.price).map(\.name))
print(products.sorted(by: \.name, ascending: false).map(\.name))

// Foundation: sorted(using:) with KeyPathComparator
let cheapFirst = products.sorted(using: KeyPathComparator(\.price))
print(cheapFirst.map(\.name))

// Several comparators: stock high to low, then name
let byStock = products.sorted(using: [
    KeyPathComparator(\.stock, order: .reverse),
    KeyPathComparator(\.name),
])
print(byStock.map { "\($0.name) \($0.stock)" })

Output

The helper sorts by price, ["Lamp", "Chair", "Desk"], and by name in reverse, ["Lamp", "Desk", "Chair"]. KeyPathComparator(\.price) gives the same price order. The array of comparators sorts by stock from high to low and breaks the tie between the two items with 4 in stock by name: Chair 4, Lamp 4, Desk 2.

6Make the type Comparable

When a type has one obvious order, such as version numbers, dates or money, conform it to Comparable. You write <, and Swift derives == for a struct whose properties are all Equatable. Then sorted(), sort(), min(), max() and sorted(by: >) all work with no closure. Keep closures for the one-off orders.

comparable.swift
struct Version: Comparable, CustomStringConvertible {
    let major: Int
    let minor: Int
    let patch: Int

    // The one operator Comparable needs; ==, >, <= and >= come for free
    static func < (a: Version, b: Version) -> Bool {
        (a.major, a.minor, a.patch) < (b.major, b.minor, b.patch)
    }

    var description: String { "\(major).\(minor).\(patch)" }
}

let releases = [
    Version(major: 1, minor: 10, patch: 0),
    Version(major: 1, minor: 2, patch: 7),
    Version(major: 2, minor: 0, patch: 1),
    Version(major: 1, minor: 2, patch: 3),
]

// Comparable types sort with no closure
print(releases.sorted())
print(releases.sorted(by: >))

// min(), max() and comparisons use the same order
if let newest = releases.max(), let oldest = releases.min() {
    print("newest", newest, "oldest", oldest)
}
print(Version(major: 1, minor: 10, patch: 0) > Version(major: 1, minor: 9, patch: 9))

Output

Because the fields compare as numbers, 1.10.0 sorts after 1.2.7: [1.2.3, 1.2.7, 1.10.0, 2.0.1]. Passing the > operator itself to sorted(by:) reverses the order, and max() and min() return 2.0.1 and 1.2.3. Without the conformance, sorted() fails with referencing instance method 'sorted()' on 'Sequence' requires that 'Version' conform to 'Comparable'.

7Which should you use?

MethodResultBest for
xs.sorted { $0.age < $1.age }New arrayMost sorts by one property; works on let
xs.sort { $0.age < $1.age }Sorts in placeA var you no longer need in the old order
($0.a, $0.b) < ($1.a, $1.b)TiebreakersSeveral properties in the same direction
localizedStandardCompareNeeds FoundationNames and file names people read
sorted(using: KeyPathComparator(…))Needs FoundationSort keys chosen at run time, mixed directions
Comparable + sorted()No closureTypes with one natural order: versions, money

Frequently asked questions

What is the difference between sort() and sorted() in Swift?

sorted() and sorted(by:) return a new array and leave the original unchanged, so they work on a let. sort() and sort(by:) reorder the array in place and return nothing, so the array must be a var; on a let the compiler says cannot use mutating member on immutable value: 'ages' is a 'let' constant.

How do I sort an array in descending order in Swift?

Flip the comparison: people.sorted { $0.age > $1.age }. For a Comparable element type, pass the operator itself: numbers.sorted(by: >). With Foundation, KeyPathComparator(\.age, order: .reverse) does the same. Calling .reversed() on an ascending result also works, but it reverses the order of equal elements too.

Why does sorted() not compile on my array of structs?

The no-argument sorted() needs a Comparable element type, and your struct isn't one. The error reads referencing instance method 'sorted()' on 'Sequence' requires that 'Person' conform to 'Comparable'. Pass a closure, people.sorted { $0.age < $1.age }, or conform the type to Comparable by writing a < function.

Is Swift's sort stable?

Yes. The standard library documentation for sort and sorted says: "The sorting algorithm is guaranteed to be stable." Elements your closure treats as equal keep their order, so you can sort by a secondary key first and then by the primary one. Older answers that say Swift's sort is not stable predate that wording.

Should the closure use < or <=?

Use <. The closure must return false when the two elements are equal. With <=, equal elements count as out of order and the sort stops being stable: sorting [(1, "a"), (1, "b"), (1, "c"), (0, "d")] by the number gives ["d", "a", "b", "c"] with < but ["d", "c", "b", "a"] with <=.

How do I sort objects by a Date property?

Date is Comparable, so compare it like a number: images.sort { $0.created < $1.created } puts the oldest first and > the newest. The same closure works for class instances: a final class ImageFile with a fileID sorts with images.sort { $0.fileID > $1.fileID }.

Run it yourself

Open any of these in the full Swift editor to tweak, run and share.

Swift playground