Skip to content

Instantly share code, notes, and snippets.

@goopi
Forked from mikeash/test.m
Last active December 29, 2015 18:09

Revisions

  1. goopi renamed this gist Nov 29, 2013. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @mikeash mikeash created this gist Jul 9, 2012.
    69 changes: 69 additions & 0 deletions test.m
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    // clang -framework Foundation -fobjc-arc -O3 test.m

    #import <Foundation/Foundation.h>


    @interface Slice : NSObject
    @property NSInteger start;
    @property NSInteger length;
    @end
    @implementation Slice
    @end

    @interface NSNumber (SliceCreation)

    - (Slice *): (NSInteger)length;

    @end

    @implementation NSNumber (SliceCreation)

    - (Slice *): (NSInteger)length
    {
    Slice *slice = [[Slice alloc] init];
    [slice setStart: [self integerValue]];
    [slice setLength: length];
    return slice;
    }

    @end

    @interface NSArray (Slicing)

    - (id)objectForKeyedSubscript: (id)subscript;

    @end

    @implementation NSArray (slicing)

    - (id)objectForKeyedSubscript: (id)subscript
    {
    Slice *slice = subscript;
    return [self subarrayWithRange: NSMakeRange([slice start], [slice length])];
    }

    @end

    int main(int argc, char **argv)
    {
    @autoreleasepool
    {
    NSMutableArray *array = [NSMutableArray array];
    for(int i = 0; i < 100; i++)
    [array addObject: @(i * i)];

    NSArray *sliced = array[[@5:8]];
    NSLog(@"%@", sliced);
    }
    }

    // 2012-07-09 17:15:12.705 a.out[84967:707] (
    // 25,
    // 36,
    // 49,
    // 64,
    // 81,
    // 100,
    // 121,
    // 144
    // )