3

I am using this to sort components in an array in Swift:

myArray = myArray.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }

However, it gives me the following result:

[18C, 18L, 18R, 22, 24, 27, 36C, 36L, 36R, 4, 6, 9]

Is it possible to sort it the right way, i.e.

[4, 6, 9, 18C, 18L, 18R, 22, 24, 27, 36C, 36L, 36R]
0

1 Answer 1

8

You can use compare with .NumericSearch:

array.sortInPlace { $0.compare($1, options: .NumericSearch) == .OrderedAscending }

or

let array2 = array.sort { $0.compare($1, options: .NumericSearch) == .OrderedAscending }
Sign up to request clarification or add additional context in comments.

5 Comments

In Swift 2 sorted() has been replaced by sort().
This does not work if the entry begins with a String instead of a number.
@MountainMan: That is not true. Try it with the array ["file1.txt", "file10.txt", "file2.txt"].
Can you write an extension for using it esier?
Yes, you can, if you want.

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.