arraysswiftmax

What is the return value of Array.max when array contains NaN?


Looking at the documentation for Array.max (https://developer.apple.com/documentation/swift/array/max()), I see it says that it returns "the sequence’s maximum element."

I wonder how that's defined when the array in question is an array of Double, and the array contains one or more NaN's and one or more other Double values. In the text, "maximum" is undefined. If it means a value x such that x >= y is true for every other value y, then array does not have a maximum element. In that case, does Array.max return nil, or what? The documentation mentions returning nil when the array is empty; is it possible there's an unstated additional case?

As a practical solution, I can see that it might be workable to return either NaN or the maximum of the non-NaN values in the array. Indeed, trying an example seems to show that this last alternative is actually implemented, but the documentation doesn't say anything about that.

I'd rather work with a stated policy instead of trying to infer it and hoping for the best. Does anyone know of any documentation for Array.max which covers what appears to be the actual implementation?


Solution

  • This is an open issue - #43623, which is about the global min and max functions. See also #43864, which asks about Array.min and Array.max and has been closed as a duplicate of #43623.

    The documentation for Comparable notes that some values of a conforming type (e.g. nan) can be excluded from the total order established by the Comparable conformance.

    A conforming type may contain a subset of values which are treated as exceptional—that is, values that are outside the domain of meaningful arguments for the purposes of the Comparable protocol. For example, the special “not a number” value for floating-point types (FloatingPoint.nan) compares as neither less than, greater than, nor equal to any normal floating-point value. Exceptional values need not take part in the strict total order.

    Based on this, I would conclude that the behaviour of Array.min and Array.max when the array contains nan is currently unspecified.