Correct way to find max in an Array in Swift

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

    The other answers are all correct, but don't forget you could also use collection operators, as follows:

    var list = [1, 2, 3, 4]
    var max: Int = (list as AnyObject).valueForKeyPath("@max.self") as Int
    

    you can also find the average in the same way:

    var avg: Double = (list as AnyObject).valueForKeyPath("@avg.self") as Double
    

    This syntax might be less clear than some of the other solutions, but it's interesting to see that -valueForKeyPath: can still be used :)

提交回复
热议问题