Instance Method インスタンスメソッド

sorted(by:)

Returns the elements of the sequence, sorted using the given predicate as the comparison between elements. 与えられた述部を要素間の比較として使ってソートされた、シーケンスの要素を返します。

Declaration 宣言

func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]

Parameters パラメータ

areInIncreasingOrder

A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. ある述部、それはそれの最初の引数がそれの2番目の引数の前に並べられるべきならばtrueを返します;そうでなければ、false

Return Value 戻り値

A sorted array of the sequence’s elements. このシーケンス要素のソート済み配列。

Discussion 解説

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 should be ordered before the second. The elements of the resulting array are ordered according to the given predicate. あなたがComparableプロトコルに準拠しない要素からなるシーケンスをソートしたい場合、最初の要素が2番目の前に並べられるべき時はtrueを返す述部をこのメソッドに渡してください。結果の配列の要素は、与えられた述部にしたがって並べられます。

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. 以下の例では、その述部はあつらえのHTTPResponse型の配列に対してある順序付けを提供します。この述部はエラーを成功の前に並べて、そしてそれらエラー応答をそのエラーコードによってソートします。


enum HTTPResponse {
    case ok
    case error(Int)
}


let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
let sortedResponses = responses.sorted {
    switch ($0, $1) {
    // Order errors by code
    case let (.error(aCode), .error(bCode)):
        return aCode < bCode


    // All successes are equivalent, so none is before any other
    case (.ok, .ok): return false


    // Order errors before successes
    case (.error, .ok): return true
    case (.ok, .error): return false
    }
}
print(sortedResponses)
// Prints "[.error(403), .error(404), .error(500), .ok, .ok]"

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 areInIncreasingOrder parameter. あなたはまた、このメソッドを使ってComparableプロトコルに準拠する要素を降順でソートすることができます。あなたのシーケンスを降順にソートするには、より大きい演算子(>)をareInIncreasingOrderパラメータとして渡してください。


let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let descendingStudents = students.sorted(by: >)
print(descendingStudents)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

Calling the related sorted() method is equivalent to calling this method and passing the less-than operator (<) as the predicate. 関連したsorted()メソッドを呼び出すことは、このメソッドを呼び出して、より小さい演算子(<)を述部として渡すことと等しいです。


print(students.sorted())
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
print(students.sorted(by: <))
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold: 述部は、それら要素に対して厳密弱順序でなければなりません。すなわち、何らかの要素ab、そしてcに対して、以下の条件が保持されなければなりません:

  • areInIncreasingOrder(a, a) is always false. (Irreflexivity) areInIncreasingOrder(a, a)は常にfalseである。(非反射)

  • If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability) areInIncreasingOrder(a, b)areInIncreasingOrder(b, c)が両方ともtrueならば、そのときareInIncreasingOrder(a, c)もまたtrueである。(推移的比較性)

  • Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability) 2つの要素は、述部によるとどちらもが他の前に並べられるならば比較できないabが比較できないならば、そしてbcが比較できないならば、そのときacもまた比較できない。(推移的比較不能性)

The sorting algorithm is not guaranteed to be stable. A stable sort preserves the relative order of elements for which areInIncreasingOrder does not establish an order. このソートアルゴリズムは、安定であることを保証されません。安定ソートは、それに対してareInIncreasingOrderが順序を確立しない要素らの相対順序を保存します。

Complexity: O(n log n), where n is the length of the sequence. 計算量:O(n log n)、ここでnはシーケンスの長さです。

See Also 参照

Reordering an Array's Elements 配列の要素を再配列します