Collections ยท SWIFT RECIPE

Sort an array of records

Sort by a property without changing the original array.

main.swift
struct Person { let name: String; let score: Int }
let people = [Person(name: "Sam", score: 8), Person(name: "Alex", score: 10)]
let ranked = people.sorted {
    if $0.score == $1.score { return $0.name < $1.name }
    return $0.score > $1.score
}
for person in ranked { print("\(person.name): \(person.score)") }

How it works

sorted returns a new array. Supply a strict ordering and a secondary comparison when ties need deterministic handling. Use sort to mutate an array in place.

EXPECTED OUTPUT
Alex: 10
Sam: 8

Keep in mind

For user-visible names, consider localized comparison.

Read the Swift language reference