Swift下标

还记得字典吗?

 

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. var numberOfLegs= ["spider": 8,"ant": 6, "cat":4]  
  2. numberOfLegs["bird"]= 2  

 

 

["bird"]就是下标 下标可以在类和结构体中定义。

定义下标

 

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. subscript(index: Int) -> Int {  
  2. get {  
  3. //return anappropriate subscript value here  
  4. }  
  5. set(newValue) {  
  6. // perform a suitable settingaction here  
  7. }  
  8. }  

 

 

 

只读下标

 

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. subscript(index: Int) -> Int {  
  2.    
  3. //return anappropriate subscript value here  
  4.    
  5. }  
  6.    

 

 

实例:

 

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. struct TimesTable {  
  2.    let multiplier: Int  
  3.     subscript(index: Int) ->Int {  
  4.          return multiplier * index  
  5.       }  
  6.  }  
  7.  let threeTimesTable = TimesTable(multiplier: 3)  
  8.  println("sixtimes three is \(threeTimesTable[6])")  
  9. // prints"six times three is 18"  

 

 

 

Swift交流讨论论坛论坛:http://www.cocoagame.net

欢迎加入Swift技术交流群:362298485

猜你喜欢

转载自guandongsheng.iteye.com/blog/2086630