Swiftly

Swift 5.1 references for busy coders

sorted() and sorted(by:)

sorted() and sorted(by:) are functional methods that return the elements of a sequence sorted using a particular predicate.

sorted()

Sorts a sequence of elements without a custom predicate. Requires that the elements are of a type that conforms to Comparable.

let numbers = [4, 200, 75, 0]
let numbersSorted = numbers.sorted()
print(numbersSorted) // [0, 4, 75, 200]

sorted(by:)

Sorts a sequence of elements with a custom predicate.

Int examples

let numbers = [4, 200, 75, 0]
let numbersAsceniding = numbers.sorted(by: <)
let numbersDescending = numbers.sorted(by: >)
print(numbersAsceniding) // [0, 4, 75, 200]
print(numbersDescending) // [200, 75, 4, 0]

Player example

struct Player {
  var name: String
  var score: Int
}

let players = [
  Player(name: "Louis", score: 100)
  Player(name: "Tomoko", score: 775)
  Player(name: "Isabella", score: 350)
]

let playersSortedByScore = players.sorted() {
  $0.score < $1.score
}
print(playersSortedByScore) // [main.Player(name: "Louis", score: 100), main.Player(name: "Isabella", score: 350), main.Player(name: "Tomoko", score: 775)]

In this example, it would not be possible to use .sorted(), .sorted(by: <), or .sorted(by: >) because Player does not conform to Comparable.