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

max(by:)

Returns the maximum element in the sequence, using the given predicate as the comparison between elements. シーケンスの中の最大の要素を返します、与えられた述部を要素間の比較として使います。

Declaration 宣言

@warn_unqualified_access func max(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 戻り値

The sequence’s maximum element if the sequence is not empty; otherwise, nil. シーケンスが空でないならばシーケンスの最大の要素;そうでなければnil

Discussion 解説

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もまた比較できない。(推移的比較不能性)

This example shows how to use the max(by:) method on a dictionary to find the key-value pair with the highest value. この例は、max(by:)メソッドを辞書上で使って、最も高い値を持つキー値ペアを見つける方法を示します。


let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let greatestHue = hues.max { a, b in a.value < b.value }
print(greatestHue)
// Prints "Optional((key: "Heliotrope", value: 296))"

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

See Also 参照

Finding Elements 要素を見つける