Я предполагаю, что у вас есть NSIndexSet:
let original = IndexSet(arrayLiteral: 0, 3, 5).union(IndexSet(integersIn: 8...9)).union( IndexSet.init(arrayLiteral: 12,14)).union(IndexSet(integersIn: 17...19)).union(IndexSet.init(arrayLiteral: 26,27))
let nsIndex = original as! NSIndexSet
После преобразования его в IndexSet вы можете легко получить два массива.Одним из них является [NSRange], а другим - [closedRange]
let index = nsIndex as! IndexSet
let rangeView = index.rangeView
print ( Array(rangeView.enumerated().map{
NSRange.init(location:($0.element.first!) , length: ((rangeView[$0.offset + 1].first! - ($0.element.first!))))
}.dropLast()))
print ( Array(rangeView.enumerated().map{
($0.element.first!)...(rangeView[$0.offset + 1].first!) - 1
}.dropLast()))
Если это цель-C.Просто так:
NSMutableIndexSet * nsIndex = [[NSMutableIndexSet alloc] init];
[nsIndex addIndex: 0];
[nsIndex addIndex: 3];
[nsIndex addIndex: 5];
[nsIndex addIndexesInRange:NSMakeRange(8, 2)];
[nsIndex addIndex: 12];
[nsIndex addIndex: 14];
[nsIndex addIndexesInRange:NSMakeRange(17, 3)];
[nsIndex addIndex: 26];
__block int count = 0;
__block NSMutableArray * ranges = [NSMutableArray array];
[nsIndex enumerateRangesUsingBlock:^(NSRange range, BOOL * _Nonnull stop) {
count ++;
[ranges addObject:[NSValue valueWithRange: range]];
}];
NSMutableArray * result = [NSMutableArray array];
for (NSUInteger location = 0 ; location < count - 1 ; location++) {
NSUInteger loc = ((NSValue *) ranges[location]).rangeValue.location;
[result addObject:[NSValue valueWithRange: (NSMakeRange( loc, ((NSValue *) ranges[location + 1]).rangeValue.location - loc))]];
}
NSLog(result.description);
или с одним раундом:
__block NSUInteger temp = nsIndex.firstIndex;
__block NSMutableArray * result = [NSMutableArray array];
[nsIndex enumerateRangesWithOptions:NSEnumerationReverse usingBlock:^(NSRange range, BOOL * _Nonnull stop) {
[result insertObject: [NSValue valueWithRange: NSMakeRange(range.location, temp - range.location)] atIndex:0];
temp = range.location ;
}];
result = [result subarrayWithRange:NSMakeRange(0, result.count - 1)];
NSLog(result.description);