2014-10-27 77 views

回答

5

或者,也許還有另一種varaible鍵入多個範圍?

是的,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) 
1

單個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)] 
+0

你也可以省略類型的註釋和讓編譯器推斷出類型:'變種multipleRanges = [NSMakeRange(0,2),NSMakeRange(10,1)]'。 – 2014-10-27 13:51:15

+0

@MartinR非常感謝您的編輯建議! – dasblinkenlight 2014-10-27 14:05:55