1

I have an Array of String which this Array of String is in fact an Array of Int, I want sort this Array of String with this code:

let array: [String] = ["13", "8", "10", "12", "3", "7", "1", "2", "11", "9", "6", "4", "5", "1000", "100", "0"].sorted(by: { (value1, value2) in return (value1 < value2) })

but out put is:

["0", "1", "10", "100", "1000", "11", "12", "13", "2", "3", "4", "5", "6", "7", "8", "9"]

I could use (Int(value1) < Int(value2)) for solving issue, but it is not practical in massive array size!

How can I sort my array without having to convert it to Int?

0

2 Answers 2

1

You can use localizedStandardCompare method to sort like this.

array.sort {$0.localizedStandardCompare($1) == .orderedAscending }
output: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "100", "1000"]
 
Sign up to request clarification or add additional context in comments.

2 Comments

Wow. localizedStandardCompare should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate in documents
0

You can use the NSString.compare(_:options:) method to compare strings numerically. That will correctly handle leading zeros and similar problems.

let array = ["13", "8", "10", "12", "3", "7", "1", "2", "11", "9", "6", "4", "5", "1000", "100", "0"]
let sortedArray = array.sorted { $0.compare($1, options: .numeric) == .orderedAscending }

print(sortedArray) // ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "100", "1000"]

3 Comments

IMO options numeric is only useful when sorting floating point values otherwise I just use localized standard compare.
@LeoDabus I don't like localizedStandardCompare because the documentation does not really state what the behavior of the method is and it also state that it can change with future releases.
I understand but they say it does a finder like sorting and it wouldn’t make any sense to change that behavior

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.