子脚本 (Subscripts) 定义在类、结构体和枚举中,表示访问对象、集合或序列的快捷方式,不需要再调用实例的特定的赋值和访问方法
1.语法
子脚本允许通过在实例后面的方括号传入一个或多个索引值来对实例进行访问和操作,使用 subscript 关键字,显示声明传入的参数和返回的类型
-
- subscript(index:Int)->Int{
- get{
-
- }
- set(newValue){
- //performasuitablesettingactionhere
- }
- //如果是只读属性,就是只有getter方法,那原get代码块可直接写在subscript中
- subscript(index:Int)->Int{
-
-
- //以下例子定义一个结构体,用来展示传入整数的n倍
- structTimesTable{
- letmultiplier:Int
- returnmultiplier*index
- letthreeTimesTable=TimesTable(multiplier:3)
- println("sixtimesthreeis(threeTimesTable[6])")
- //prints"sixtimesthreeis18"
2.用法
通常用来访问集合,列表或序列中的元素
varnumberOfLegs=["spider":8,"ant":6,"cat":4]
- numberOfLegs["bird"]=2
3.选项
子脚本允许任意数量的参数,并且参数类型没有限制,一个类或结构体可使用多个子脚本的实现,根据传入的参数进行区分,称为子脚本的重载
structMatrix{
- rows:Int,columns:Int
- vargrid:Double[]
- init(rows:Int,columns:Int){
- self.rows=rows
- self.columns=columns
- grid=Array(count:rows*columns,0); background-color:inherit">repeatedValue:0.0)
- funcindexIsValidForRow(row:Int,0); background-color:inherit">column:Int)->Bool{
- returnrow>=0&&row<rows&&column>=0&&column<columns
- subscript(row:Int,0); background-color:inherit">column:Int)->Double{
- assert(indexIsValidForRow(row,0); background-color:inherit">column:column),"Indexoutofrange")
- returngrid[(row*columns)+column]
- set{
- grid[(column]=newValue
- varmatrix=Matrix(rows:2,0); background-color:inherit">columns:2)
- matrix[0,0); background-color:inherit">1]=1.5
- matrix[1,0); background-color:inherit">0]=3.2
- letsomeValue=matrix[2,0); background-color:inherit">2]
- //thistriggersanassert,because[2,2]isoutsideofthematrixbounds
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|