Search code examples
swiftsortingnsarraynsdecimalnumber

Sort NSArray of NSDecimalNumber


NSDecimalNumber has a useful compare: method.

Rather then writing a wrapper around this compare method and then calling sortedArrayUsingFunction:context:, I would simply like to directly pass the NSDecimalNumber compare method to one of NSArray's sorted<...> methods.

What is the best way to do this using Swift?


Solution

  • For NSArray you can simply use sortedArrayUsingSelector() and pass the compare: method as selector:

    let array = NSArray(objects:
            NSDecimalNumber(integer: 30),
            NSDecimalNumber(integer: 20),
            NSDecimalNumber(integer: 10))
    let sorted = array.sortedArrayUsingSelector("compare:")
    // Swift 2.2 or later:
    let sorted = array.sortedArrayUsingSelector(#selector(NSNumber.compare(_:)))
    
    print(sorted) // [10, 20, 30]