我似乎无法理解 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/