Correct way to find max in an Array in Swift

前端 未结 12 1698
一整个雨季
一整个雨季 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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-29 18:44
    var numbers = [1, 2, 7, 5];    
    var val = sort(numbers){$0 > $1}[0];
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 18:59

    Here's a performance test for the solutions posted here. https://github.com/tedgonzalez/MaxElementInCollectionPerformance

    This is the fastest for Swift 5

    array.max()

    0 讨论(0)
  • 2020-11-29 19:00

    Given:

    let numbers = [1, 2, 3, 4, 5]
    

    Swift 3:

    numbers.min() // equals 1
    numbers.max() // equals 5
    

    Swift 2:

    numbers.minElement() // equals 1
    numbers.maxElement() // equals 5
    
    0 讨论(0)
提交回复
热议问题