NSRange变量是否可以包含多个范围



NSRange变量是否可能包含多个范围?类似于:

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

或者可能还有另一种适用于多个范围的可变类型?

或者可能还有另一种适用于多个范围的可变类型?

是的,NS(Mutable)IndexSet将(唯一的)无符号整数的集合存储为范围序列。

示例:创建可变索引集并添加两个范围和一个索引:

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)]

枚举所有索引:

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

枚举所有范围:

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

测试成员资格:

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

但请注意,NSIndexSet表示集合,即不存在重复元素,并且元素的顺序无关紧要。这可能会也可能不会根据你的需要发挥作用。示例:

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

单个NSRange变量可以容纳单个范围。如果你需要存储几个范围,制作一个数组:

var multipleRanges: [NSRange] = [NSMakeRange(0, 2), NSMakeRange(10, 1)]
//                  ^       ^
//                  |       |
// This tells Swift that you are declaring an array, and that array elements
// are of NSRange type.

您也可以省略类型,让编译器为您推断它:

// This is the same declaration as above, but now the type of array element
// is specified implicitly through the type of initializer elements:
var multipleRanges = [NSMakeRange(0, 2), NSMakeRange(10, 1)]

最新更新