.sort not working in Swift 2.0

亡梦爱人 提交于 2019-12-19 10:31:47

问题


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.

for combination in myCombinations {
        combination.sort({$0 < $1})
        print("\(combination)")
    }

Here's my code to sort out the array and here's my result.

["lys", "dyt", "lrt"]
["lys", "dyt", "gbc"]
["lys", "dyt", "lbc"]

I also got a warning that says "Result of call to 'sort' is unused" Could anyone help me out with this?

Thanks.


回答1:


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"]]


来源:https://stackoverflow.com/questions/32920814/sort-not-working-in-swift-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!