Correct way to find max in an Array in Swift

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

    In Swift 2.0, the minElement and maxElement become methods of SequenceType protocol, you should call them like:

    let a = [1, 2, 3]
    print(a.maxElement()) //3
    print(a.minElement()) //1
    

    Using maxElement as a function like maxElement(a) is unavailable now.

    The syntax of Swift is in flux, so I can just confirm this in Xcode version7 beta6.

    It may be modified in the future, so I suggest that you'd better check the doc before you use these methods.

提交回复
热议问题