实例方法
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 DefaultIndices max()用法及代码示例
- Swift DefaultIndices map(_:)用法及代码示例
- Swift DefaultIndices min(by:)用法及代码示例
- Swift DefaultIndices min()用法及代码示例
- Swift DefaultIndices endIndex用法及代码示例
- Swift DefaultIndices index(_:offsetBy:limitedBy:)用法及代码示例
- Swift DefaultIndices prefix(through:)用法及代码示例
- Swift DefaultIndices reduce(_:_:)用法及代码示例
- Swift DefaultIndices allSatisfy(_:)用法及代码示例
- Swift DefaultIndices shuffled()用法及代码示例
- Swift DefaultIndices shuffled(using:)用法及代码示例
- Swift DefaultIndices first用法及代码示例
- Swift DefaultIndices prefix(_:)用法及代码示例
- Swift DefaultIndices lexicographicallyPrecedes(_:)用法及代码示例
- Swift DefaultIndices index(_:offsetBy:)用法及代码示例
- Swift DefaultIndices compactMap(_:)用法及代码示例
- Swift DefaultIndices suffix(_:)用法及代码示例
- Swift DefaultIndices dropLast(_:)用法及代码示例
- Swift DefaultIndices last(where:)用法及代码示例
- Swift DefaultIndices filter(_:)用法及代码示例
- Swift DefaultIndices lastIndex(of:)用法及代码示例
- Swift DefaultIndices contains(_:)用法及代码示例
- Swift DefaultIndices prefix(upTo:)用法及代码示例
- Swift DefaultIndices split(separator:maxSplits:omittingEmptySubsequences:)用法及代码示例
- Swift DefaultIndices contains(where:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 DefaultIndices max(by:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
