Swift:subscript


本文轉載自:http://blog.csdn.net/sinat_27706697/article/details/47122137 感謝作者:秋恨雪

通常情況下,我們在使用數組(Array)或字典(Dictionary)時會使用到下標。其實在Swift中,我們還可以給類、結構、枚舉等自定義下標(subscript)。

一、基本使用

 

 
  1. struct TimesTable {  
  2.     let multiplier: Int  
  3.       
  4.     subscript(index: Int) -> Int {  
  5.         return multiplier * index  
  6.     }  
  7. }  

我在TimesTable這個結構中自定義了一個subscript,並且這個subscript類似於方法,看上去它的類型為 Int -> Int。

 

然后在調用的時候,就可以使用"[index]"這樣的形式取值。

 
  1. let threeTimesTable = TimesTable(multiplier: 3)  
  2. println("six times three is \(threeTimesTable[7])")  

 

二、使用subscript可以刪除字典中的某個特定的key-value

 
  1. var numberOfLegs = ["spider":8,"ant":6,"cat":4]  
  2. numberOfLegs["ant"] = nil  
  3. println(numberOfLegs.count)  

上面的numberOfLegs初始時候它有三對值,當進行numberOfLegs["ant"] = nil 操作后,相當於key為"ant"的key-value被刪除了,所以打印的結果為2。

 

三、subscript中的索引參數不一定永遠是一個Int類型的index,它也可以有多個參數。

例如,我們可以使用subscript將一維數組模擬成二維數組。

 
  1. struct Matrix {  
  2.     let rows: Int  
  3.     let cols: Int  
  4.     var grid: [Double]  
  5.     init(rows: Int, cols: Int) {  
  6.         self.rows = rows  
  7.         self.cols = cols  
  8.         self.grid = Array(count: rows * cols, repeatedValue: 0.0)  
  9.     }  
  10.       
  11.     func indexIsValidForRow(row: Int, col: Int) -> Bool {  
  12.         return row >= 0 && row < rows && col >= 0 && col < cols;  
  13.     }  
  14.       
  15.     subscript(row: Int, col: Int) -> Double {  
  16.         get {  
  17.             assert(indexIsValidForRow(row, col: col), "index out of range")  
  18.             return grid[row * cols + col]  
  19.         }  
  20.         set {  
  21.             assert(indexIsValidForRow(row, col: col), "index out of range")  
  22.             grid[row * cols + col] = newValue  
  23.         }  
  24.     }  
  25. }  

代碼中的grid成員屬性是一個含有rows * cols 個元素的一維數組。

 

然后定義一個subscript, 這里的下標有兩個:row和col。然后根據具體的輸入參數,從grid數組中取出對應的值。所以這里的下標只是模擬,看起來輸入row和col,但實際還是從一維數組grid中取值。

調用效果如下:

 

[objc]  view plain  copy
 
  1. var matrix = Matrix(rows: 3, cols: 4)  
  2. matrix[2, 1] = 3.4  
  3. matrix[1, 2] = 5  
  4. //  
  5. var some2 = matrix[1, 2]  
  6. println("some:\(some2)")  

四、獲取數組中指定索引位置的子數組,我們可以在Array的擴展中用subscript來實現。

 

 
  1. extension Array {  
  2.     subscript(input: [Int]) -> ArraySlice<T> {  
  3.         get {  
  4.             var array = ArraySlice<T>()  
  5.             for i in input {  
  6.                 assert(i < self.count, "index out of range")  
  7.                 array.append(self[i])  
  8.             }  
  9.             return array  
  10.         }  
  11.         set {  
  12.             // i表示數組input自己的索引,index表示數組self的索引  
  13.             for (i, index) in enumerate(input) {  
  14.                 assert(index < self.count, "index out of range")  
  15.                 self[index] = newValue[i]  
  16.             }  
  17.         }  
  18.     }  
  19. }  

代碼中的input數組表示選取的Array中的某些下標。例如:

 

arr數組 

 
  1. var arr = [1, 2, 3, 4, 5]  

input數組

 

 
  1. var input = [0,2]  

那么通過input中的值在arr數組中取得的子數組為 [1, 3]

 

subscript中的get方法就是根據input中的數組的下標值取得arr數組中對應下標的子數組。

subscript中的set方法就是根據input中的數組的下標值對arr數組中對應下標的內容重新賦值。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM