Correct way to find max in an Array in Swift

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

    Updated for Swift 3/4:

    Use below simple lines of code to find the max from array;

    var num = [11, 2, 7, 5, 21]
    var result = num.sorted(){
        $0 > $1
    }
    print("max from result: \(result[0])") // 21
    

提交回复
热议问题