實例方法
max(by:)
返回序列中的最大元素,使用給定的謂詞作為元素之間的比較。
聲明
@warn_unqualified_access func max(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element?
返回值
如果序列不為空,則序列的最大元素;否則,nil
。
參數
areInIncreasingOrder
如果其第一個參數應在其第二個參數之前排序,則返回
true
的謂詞;否則,false
。
詳述
謂詞必須是元素上的strict weak ordering
。也就是說,對於任何元素 a
、 b
和 c
,必須滿足以下條件:
-
areInIncreasingOrder(a, a)
始終是false
。 (非反身性) -
如果
areInIncreasingOrder(a, b)
和areInIncreasingOrder(b, c)
都是true
,那麽areInIncreasingOrder(a, c)
也是true
。 (傳遞可比性) -
如果根據謂詞,兩個元素都沒有排在另一個之前,則兩個元素是
incomparable
。如果a
和b
不可比,b
和c
不可比,那麽a
和c
也是不可比的。 (傳遞不可比性)
此示例說明如何在字典上使用 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))"
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift Set max()用法及代碼示例
- Swift Set map(_:)用法及代碼示例
- Swift Set min()用法及代碼示例
- Swift Set min(by:)用法及代碼示例
- Swift Set subtracting(_:)用法及代碼示例
- Swift Set remove(_:)用法及代碼示例
- Swift Set prefix(upTo:)用法及代碼示例
- Swift Set subscript(_:)用法及代碼示例
- Swift Set update(with:)用法及代碼示例
- Swift Set formIntersection(_:)用法及代碼示例
- Swift Set dropFirst(_:)用法及代碼示例
- Swift Set joined(separator:)用法及代碼示例
- Swift Set elementsEqual(_:)用法及代碼示例
- Swift Set init(arrayLiteral:)用法及代碼示例
- Swift Set symmetricDifference(_:)用法及代碼示例
- Swift Set joined()用法及代碼示例
- Swift Set isDisjoint(with:)用法及代碼示例
- Swift Set shuffled()用法及代碼示例
- Swift Set contains(_:)用法及代碼示例
- Swift Set isStrictSubset(of:)用法及代碼示例
- Swift Set first(where:)用法及代碼示例
- Swift Set intersection(_:)用法及代碼示例
- Swift Set suffix(from:)用法及代碼示例
- Swift Set formSymmetricDifference(_:)用法及代碼示例
- Swift Set formUnion(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Set max(by:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。