Last active
December 17, 2015 08:48
-
-
Save beccadax/5582191 to your computer and use it in GitHub Desktop.
This gist includes a quick syntax for constructing NSIndexSets—[@0:9] and [@0:9 step:2]—and fast enumeration support for NSIndexSet (yielding NSNumbers). The result is that you can enumerate over ranges using for/in. The gist is CodeRunner ready.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface NSNumber (range) | |
- (NSIndexSet*):(NSUInteger)max; | |
- (NSIndexSet*):(NSUInteger)max step:(NSUInteger)step; | |
@end | |
@interface NSIndexSet (FastEnumeration) <NSFastEnumeration> @end | |
int main(int argc, char *argv[]) { | |
@autoreleasepool { | |
NSLog(@"vars = %@", [@0:20 step:2]); | |
for(NSNumber * i in [@0:20 step:2]) { | |
NSLog(@"i = %ld", i.integerValue); | |
} | |
} | |
} | |
@implementation NSNumber (range) | |
- (NSIndexSet*):(NSUInteger)max { | |
return [self:max step:1]; | |
} | |
- (NSIndexSet*):(NSUInteger)max step:(NSUInteger)step { | |
NSMutableIndexSet * indexes = [NSMutableIndexSet new]; | |
for(NSUInteger i = self.unsignedIntegerValue; i <= max; i += step) { | |
[indexes addIndex:i]; | |
} | |
return indexes; | |
} | |
@end | |
@implementation NSIndexSet (FastEnumeration) | |
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { | |
if(state->state == 0) { | |
// There's no good way to check for mutations without access to NSMutableIndexSet's internals, so we just set a pointer that we know will be valid and won't change. | |
state->mutationsPtr = state->extra; | |
} | |
NSUInteger index = [self indexGreaterThanOrEqualToIndex:state->state]; | |
if(index == NSNotFound) { | |
return 0; | |
} | |
__autoreleasing NSNumber * temp = @(index); | |
state->state = index + 1; | |
state->itemsPtr = stackbuf; | |
state->itemsPtr[0] = temp; | |
return 1; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment