swift - Array.max(by :) difficulty understanding

标签 swift

我似乎无法理解 Array.max(by:) 背后的想法运营商解释。

考虑以下代码行:

print([10, 2, 5, 1, 3].max { $0 > $1 })

我假设预期输出应该是 10,但实际上输出是 1。现在,我在文档中读到这个函数的唯一参数 areInIncreasingOrder 本身就是一个函数,定义为:

A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.

我似乎无法理解这种说法。为什么相邻元素放置会影响函数结果?

注意:在实际示例中,数组将由非原始类型的元素组成,例如,需要比较两个对象的日期。我知道,如果要解决上述简单示例,只需使用默认值 Array.max() 即可。运营商。

最佳答案

Quoting Steve Canon在 Swift 论坛中:

The predicate argument defines what "increasing order" is for the purposes of the function. When you use > as the predicate, you're saying that a > b implies that a is before b in the order you want to use.

在你的情况下

print([10, 2, 5, 1, 3].max { $0 > $1 })

数组元素的递增顺序为

10, 5, 3, 2, 1

并且关于该顺序的最大元素是1

如果目的是获得关于“自然排序”的最大元素,那么简单地使用

print([10, 2, 5, 1, 3].max())

关于swift - Array.max(by :) difficulty understanding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56742314/

相关文章:

swift - 在 Swift Playground 中调试断点?

ios - 有没有办法观察 UIViewPropertyAnimator 中 fractionComplete 的变化

swift - ImageView - 在启动屏幕上的所有设备上居中对齐图像

ios - 了解 Swift 中货币的 NumberFormatter

ios - 你如何检查 NSURLRequest.URL 是否为零?

ios - 我如何在键盘出现之前获取键盘框架

ios - Swift 3 - 从图库中获取所有照片

swift - Pod 安装 GPUImage 不起作用

ios - 具有容器 View 的 iPad 纵向和横向模式的不同尺寸等级

ios - 在蒙版 UIView 周围添加阴影