Correct way to find max in an Array in Swift

前端 未结 12 1816
一整个雨季
一整个雨季 2020-11-29 18:05

I\'ve so far got a simple (but potentially expensive) way:

var myMax = sort(myArray,>)[0]

And how I was taught to do it at school:

12条回答
  •  清酒与你
    2020-11-29 18:35

    Update: This should probably be the accepted answer since maxElement appeared in Swift.


    Use the almighty reduce:

    let nums = [1, 6, 3, 9, 4, 6];
    let numMax = nums.reduce(Int.min, { max($0, $1) })
    

    Similarly:

    let numMin = nums.reduce(Int.max, { min($0, $1) })
    

    reduce takes a first value that is the initial value for an internal accumulator variable, then applies the passed function (here, it's anonymous) to the accumulator and each element of the array successively, and stores the new value in the accumulator. The last accumulator value is then returned.

提交回复
热议问题