typestar

Sorting with comparators in Objective-C

A block returns ascending, same, or descending; the array obeys.

#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray<NSNumber *> *years = @[ @1971, @1959, @1977, @1965 ];

        // A comparator block returns ascending, same, or descending.
        NSArray<NSNumber *> *sorted =
            [years sortedArrayUsingComparator:
                ^NSComparisonResult(NSNumber *a, NSNumber *b) {
                    return [a compare:b];
                }];
        NSLog(@"Oldest press: %@", [sorted firstObject]);
        NSLog(@"In order: %@", [sorted componentsJoinedByString:@", "]);
    }
    return 0;
}

How it works

  1. sortedArrayUsingComparator: returns a new sorted array.
  2. [a compare:b] already speaks NSComparisonResult.
  3. The original array is untouched — immutable in, immutable out.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
463
Tokens
99
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 99 seconds.

Type this snippet

Step 3 of 3 in Enumeration, step 15 of 27 in Language basics.

← Previous Next →