Created
May 9, 2014 17:28
-
-
Save douglashill/7322eb450f957a1d4d79 to your computer and use it in GitHub Desktop.
Concise string representations of index sets, like [4-5, 16, 19-21] or alternatively [4, 5, 16, 19, 20, 21]
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
static NSString * DHStringFromRange(NSRange range); | |
@implementation NSIndexSet (DHDescription) | |
- (NSString *)dh_description | |
{ | |
return [self dh_descriptionShowingRanges:YES]; | |
} | |
- (NSString *)dh_descriptionShowingRanges:(BOOL)shouldShowAsRanges | |
{ | |
static NSString * const separator = @", "; | |
NSUInteger const firstIndex = [self firstIndex]; | |
NSMutableString * const description = [NSMutableString stringWithString:@"["]; | |
if (shouldShowAsRanges) { | |
[self enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) { | |
if (range.location != firstIndex) [description appendString:separator]; | |
[description appendString:DHStringFromRange(range)]; | |
}]; | |
} | |
else { | |
[self enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) { | |
if (idx != firstIndex) [description appendString:separator]; | |
[description appendString:[NSString stringWithFormat:@"%lu", (unsigned long)idx]]; | |
}]; | |
} | |
[description appendString:@"]"]; | |
return description; | |
} | |
@end | |
static NSString *DHStringFromRange(NSRange range) | |
{ | |
switch (range.length) { | |
case 0: | |
return @""; | |
case 1: | |
return [NSString stringWithFormat:@"%lu", (unsigned long)range.location]; | |
default: | |
return [NSString stringWithFormat:@"%lu-%lu", (unsigned long)range.location, (unsigned long)(range.location + range.length - 1)]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment