Sort an array of string containing numbers

by

By default, Sorting an array of string containing numbers is not sorted in natural order of numbers. They are sorted in natural order of string characters.

For example objects in array have property of type string which are all literal of numbers:


slot1.indexStr = “1”
slot2.indexStr = “14”
slot3.indexStr = “2”
slots = [slot1, slot2, slot3]


 slots = slots.sorted { $0.indexStr! < $1.indexStr! }

 1
 14
 2
 

It sorted alphabetically based on first character of string. What we want is to sort based on values of number.

// The Workaround


slots = slots.sorted { $0.indexStr!.localizedStandardCompare($1.indexStr!)  == .orderedAscending }
        
1 2 14

slots = [slots sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
    return [obj1.indexStr localizedStandardCompare:obj2.indexStr] == NSOrderedAscending;
}];
        
1 2 14

We are using localizedStandardCompare

Compares strings as sorted by the Finder.

You might also like: AVAudioPlayer not playing any sound

You might also like: Blurry Pixel Font in SpriteKit bug

You might also like: MFMessageComposeViewController shows blank white screen issue

More Articles

Recommended posts