Correct way to find max in an Array in Swift

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

    You can use with reduce:

    let randomNumbers = [4, 7, 1, 9, 6, 5, 6, 9]
    let maxNumber = randomNumbers.reduce(randomNumbers[0]) { $0 > $1 ? $0 : $1 } //result is 9
    

提交回复
热议问题