本文轉載自:http://blog.csdn.net/sinat_27706697/article/details/47122137 感謝作者:秋恨雪
通常情況下,我們在使用數組(Array)或字典(Dictionary)時會使用到下標。其實在Swift中,我們還可以給類、結構、枚舉等自定義下標(subscript)。
一、基本使用
- struct TimesTable {
- let multiplier: Int
- subscript(index: Int) -> Int {
- return multiplier * index
- }
- }
我在TimesTable這個結構中自定義了一個subscript,並且這個subscript類似於方法,看上去它的類型為 Int -> Int。
然后在調用的時候,就可以使用"[index]"這樣的形式取值。
- let threeTimesTable = TimesTable(multiplier: 3)
- println("six times three is \(threeTimesTable[7])")
二、使用subscript可以刪除字典中的某個特定的key-value
- var numberOfLegs = ["spider":8,"ant":6,"cat":4]
- numberOfLegs["ant"] = nil
- println(numberOfLegs.count)
上面的numberOfLegs初始時候它有三對值,當進行numberOfLegs["ant"] = nil 操作后,相當於key為"ant"的key-value被刪除了,所以打印的結果為2。
三、subscript中的索引參數不一定永遠是一個Int類型的index,它也可以有多個參數。
例如,我們可以使用subscript將一維數組模擬成二維數組。
- struct Matrix {
- let rows: Int
- let cols: Int
- var grid: [Double]
- init(rows: Int, cols: Int) {
- self.rows = rows
- self.cols = cols
- self.grid = Array(count: rows * cols, repeatedValue: 0.0)
- }
- func indexIsValidForRow(row: Int, col: Int) -> Bool {
- return row >= 0 && row < rows && col >= 0 && col < cols;
- }
- subscript(row: Int, col: Int) -> Double {
- get {
- assert(indexIsValidForRow(row, col: col), "index out of range")
- return grid[row * cols + col]
- }
- set {
- assert(indexIsValidForRow(row, col: col), "index out of range")
- grid[row * cols + col] = newValue
- }
- }
- }
代碼中的grid成員屬性是一個含有rows * cols 個元素的一維數組。
然后定義一個subscript, 這里的下標有兩個:row和col。然后根據具體的輸入參數,從grid數組中取出對應的值。所以這里的下標只是模擬,看起來輸入row和col,但實際還是從一維數組grid中取值。
調用效果如下:
- var matrix = Matrix(rows: 3, cols: 4)
- matrix[2, 1] = 3.4
- matrix[1, 2] = 5
- //
- var some2 = matrix[1, 2]
- println("some:\(some2)")
四、獲取數組中指定索引位置的子數組,我們可以在Array的擴展中用subscript來實現。
- extension Array {
- subscript(input: [Int]) -> ArraySlice<T> {
- get {
- var array = ArraySlice<T>()
- for i in input {
- assert(i < self.count, "index out of range")
- array.append(self[i])
- }
- return array
- }
- set {
- // i表示數組input自己的索引,index表示數組self的索引
- for (i, index) in enumerate(input) {
- assert(index < self.count, "index out of range")
- self[index] = newValue[i]
- }
- }
- }
- }
代碼中的input數組表示選取的Array中的某些下標。例如:
arr數組
- var arr = [1, 2, 3, 4, 5]
input數組
- var input = [0,2]
那么通過input中的值在arr數組中取得的子數組為 [1, 3]
subscript中的get方法就是根據input中的數組的下標值取得arr數組中對應下標的子數組。
subscript中的set方法就是根據input中的數組的下標值對arr數組中對應下標的內容重新賦值。