Skip to content

Instantly share code, notes, and snippets.

@douglashill
Created May 9, 2014 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglashill/7322eb450f957a1d4d79 to your computer and use it in GitHub Desktop.
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]
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