Igor Tupitsyn
Igor Tupitsyn

Reputation: 1193

Swift: sorting of array is not done correctly

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]

Upvotes: 3

Views: 1097

Answers (1)

Rob
Rob

Reputation: 437392

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 }

Upvotes: 8

Related Questions