2

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
  • I think you should override de sorted arrays in myCombinations. That should fix your issue and your warning Commented Oct 3, 2015 at 9:18

1 Answer 1

7

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"]]
Sign up to request clarification or add additional context in comments.

2 Comments

Best explanation I've seen!! Thank you.
Be careful, this has changed again in Swift 3, where sort is the mutating method, and sorted is the one returning a new array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.