Skip to content

Instantly share code, notes, and snippets.

@GuanshanLiu
Forked from mikeash/test.m
Created July 10, 2012 07:18
Show Gist options
  • Save GuanshanLiu/3081769 to your computer and use it in GitHub Desktop.
Save GuanshanLiu/3081769 to your computer and use it in GitHub Desktop.
Cocoa array slicing
#import <Foundation/Foundation.h>
@interface Slice : NSObject
@property NSInteger from;
@property NSInteger to;
@property NSInteger step;
@end
@implementation Slice
@end
@interface NSNumber (SliceCreation)
- (Slice *):(NSInteger)to;
- (Slice *):(NSInteger)to :(NSInteger)step;
@end
@implementation NSNumber (SliceCreation)
- (Slice *):(NSInteger)to {
return [self :to :1];
}
- (Slice *):(NSInteger)to :(NSInteger)step
{
Slice *slice = [[Slice alloc] init];
slice.from = [self integerValue];
slice.to = to;
slice.step = step;
return slice;
}
@end
@interface NSArray (Slicing)
- (id)objectForKeyedSubscript: (id)subscript;
@end
@implementation NSArray (slicing)
- (id)objectForKeyedSubscript: (id)subscript
{
Slice *slice = subscript;
NSMutableArray *subArray = [NSMutableArray array];
NSInteger start = slice.from < 0 ? slice.from + self.count : slice.from;
NSInteger end = slice.to < 0 ? slice.to + self.count : slice.to;
for(NSInteger i = start; (i < end && slice.step > 0) || (i > end && slice.step < 0) ; i += slice.step) {
[subArray addObject:[self objectAtIndex:i]];
}
return subArray;
}
@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[[@-1:90:-1]];
NSLog(@"%@", sliced);
}
}
/*
2012-07-10 15:17:32.163 NSArraySlice[4600:303] (
9801,
9604,
9409,
9216,
9025,
8836,
8649,
8464,
8281
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment