Correct way to find max in an Array in Swift

前端 未结 12 1812
一整个雨季
一整个雨季 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:36

    With Swift 1.2 (and maybe earlier) you now need to use:

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

    For working with Double values I used something like this:

    let nums = [1.3, 6.2, 3.6, 9.7, 4.9, 6.3];
    let numMax = nums.reduce(-Double.infinity, combine: { max($0, $1) })
    

提交回复
热议问题