Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.
- Xcode 8.0+
- Swift Standard Library
In Increasing Order
A predicate that returns
trueif its first argument should be ordered before its second argument; otherwise,
A sorted array of the sequence’s elements.
When you want to sort a sequence of elements that don’t conform to the
Comparable protocol, pass a predicate to this method that returns
true when the first element passed should be ordered before the second. The elements of the resulting array are ordered according to the given predicate.
The predicate must be a strict weak ordering over the elements. That is, for any elements
c, the following conditions must hold:
In Increasing Order(a, a)
In Increasing Order(a, b)
In Increasing Order(b, c)
In Increasing Order(a, c)
true. (Transitive comparability)
Two elements are incomparable if neither is ordered before the other according to the predicate. If
bare incomparable, and
care incomparable, then
care also incomparable. (Transitive incomparability)
The sorting algorithm is not stable. A nonstable sort may change the relative order of elements for which
are does not establish an order.
In the following example, the predicate provides an ordering for an array of a custom
HTTPResponse type. The predicate orders errors before successes and sorts the error responses by their error code.
You also use this method to sort elements that conform to the
Comparable protocol in descending order. To sort your sequence in descending order, pass the greater-than operator (
>) as the
Calling the related
sorted() method is equivalent to calling this method and passing the less-than operator (
<) as the predicate.