Can the NSRange variable contain multiple ranges?

advertisements

Is it possible that NSRange variable contains multiple ranges? Something like:

 var multipleRanges: NSRange = [NSMakeRange(0, 2), NSMakeRange(10, 1), ...]

Or maybe there is another varaible type for multiple ranges?


Or maybe there is another varaible type for multiple ranges?

Yes, NS(Mutable)IndexSet stores a collection of (unique) unsigned integers as a sequence of ranges.

Example: Create mutable index set and add two ranges and a single index:

let indexSet = NSMutableIndexSet()
indexSet.addIndexesInRange(NSMakeRange(0, 2))
indexSet.addIndexesInRange(NSMakeRange(10, 3))
indexSet.addIndex(5)
println(indexSet)
// <NSMutableIndexSet: 0x10050a510>[number of indexes: 6 (in 3 ranges), indexes: (0-1 5 10-12)]

Enumerate all indexes:

indexSet.enumerateIndexesUsingBlock { (index, stop) -> Void in
    println(index)
}
// Output: 0 1 5 10 11 12

Enumerate all ranges:

indexSet.enumerateRangesUsingBlock { (range, stop) -> Void in
    println(range)
}
// Output: (0,2) (5,1) (10,3)

Test membership:

if indexSet.containsIndex(11) {
    // ...
}

But note that NSIndexSet represents a set, i.e. there are no duplicate elements, and the order of elements does not matter. This may or may not be useful depending on your needs. Example:

let indexSet = NSMutableIndexSet()
indexSet.addIndexesInRange(NSMakeRange(0, 4))
indexSet.addIndexesInRange(NSMakeRange(2, 4))
indexSet.enumerateRangesUsingBlock { (range, stop) -> Void in
    println(range)
}
// Output: (0,6)