Yearim Kaya Kim
Yearim Kaya Kim

Reputation: 79

.sort not working in Swift 2.0

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.

Upvotes: 2

Views: 1800

Answers (1)

Eric Aya
Eric Aya

Reputation: 70096

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

Upvotes: 7

Related Questions