.sort not working in Swift 2.0

后端 未结 1 1714
無奈伤痛
無奈伤痛 2021-01-15 01:44

I\'m trying to sort my arrays of combinations i currently have. It is multidimensional array, but I only need to sort out the array that\'s inside for now.

         


        
相关标签:
1条回答
  • 2021-01-15 02:06

    In Swift 2, what was sort is now sortInPlace (and what was sorted is now sort), and both methods are to be called on the array itself (they were previously global functions).

    When you call combination.sort({$0 < $1}) you actually return a sorted array, you're not sorting the source array in place.

    And in your example the result of combination.sort({$0 < $1}) is not assigned to any variable, that's what the compiler is telling you with this error message.

    Assign the result of sort:

    let sortedArray = combination.sort({$0 < $1})
    print(sortedArray)
    

    If you want to get an array of sorted arrays, you can use map instead of a loop:

    let myCombinations = [["lys", "dyt", "lrt"], ["lys", "dyt", "gbc"], ["lys", "dyt", "lbc"]]
    
    let sortedCombinations = myCombinations.map { $0.sort(<) }
    
    print(sortedCombinations)  // [["dyt", "lrt", "lys"], ["dyt", "gbc", "lys"], ["dyt", "lbc", "lys"]]
    
    0 讨论(0)
提交回复
热议问题