Swift: array sorting is wrong

I use this to sort components in an array in Swift:

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

      

However, this gives me the following output:

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

      

Is it possible to sort it correctly, i.e.

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

      

+3


source to share


1 answer


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 }

      

+8


source







All Articles