Sorts the collection in place, using the given predicate as the comparison between elements.
- Xcode 8.0+
- Swift Standard Library
A predicate that returns
trueif its first argument should be ordered before its second argument; otherwise,
arethrows an error during the sort, the elements may be in a different order, but none will be lost.
In Increasing Order
When you want to sort a collection of elements that don’t conform to the
Comparable protocol, pass a closure to this method that returns
true when the first element should be ordered before the second.
In the following example, the closure provides an ordering for an array of a custom enumeration that describes an HTTP response. The predicate orders errors before successes and sorts the error responses by their error code.
Alternatively, use this method to sort a collection of elements that do conform to
Comparable when you want the sort to be descending instead of ascending. Pass the greater-than operator (
>) operator as the predicate.
are 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 guaranteed to be stable. A stable sort preserves the relative order of elements for which
are does not establish an order.
Complexity: O(n log n), where n is the length of the collection.