Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.max(by:) difficulty understanding

Tags:

swift

I can't seem to understand the idea behind the Array.max(by:) operator explanation.

Consider the following line of code:

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

I would assume that the expected output should be 10, but actually the output is 1. Now, I've read in the docs that the only argument of this function, areInIncreasingOrder, itself being a function, is defined as:

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

I just can't seem to understand this statement. Why does the adjacent element placement affect the function result?

Note: In the real-world example, the array would be consisted of non-primitive-type elements, where one would need to, for an example, compare dates of two objects. I understand that, if the aforementioned, simple example, was to be solved, one would simply do it with the default, Array.max() operator.

like image 405
haste Avatar asked Mar 07 '26 05:03

haste


1 Answers

Quoting Steve Canon in the Swift forum:

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.

In your case

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

the increasing order of the array elements is

10, 5, 3, 2, 1

and the maximal element with respect to that order is 1.

If the intention is to get the maximal element with respect to the “natural ordering” then use simply

print([10, 2, 5, 1, 3].max())
like image 173
Martin R Avatar answered Mar 09 '26 21:03

Martin R