Swift 子脚本(十一)

前端之家收集整理的这篇文章主要介绍了Swift 子脚本(十一)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
子脚本 (Subscripts)

定义在类、结构体和枚举中,表示访问对象、集合或序列的快捷方式,不需要再调用实例的特定的赋值和访问方法

1.语法

子脚本允许通过在实例后面的方括号传入一个或多个索引值来对实例进行访问和操作,使用 subscript 关键字,显示声明传入的参数和返回的类型
[objc] view plain copy
  1. //newValue的类型必须和脚本定义的返回类型相同
  2. subscript(index:Int)->Int{
  3. get{
  4. //returnanappropriatesubscriptvaluehere
  5. }
  6. set(newValue){
  7. //performasuitablesettingactionhere
  8. }
  9. //如果是只读属性,就是只有getter方法,那原get代码块可直接写在subscript中
  10. subscript(index:Int)->Int{
  11. //以下例子定义一个结构体,用来展示传入整数的n倍
  12. structTimesTable{
  13. letmultiplier:Int
  14. returnmultiplier*index
  15. letthreeTimesTable=TimesTable(multiplier:3)
  16. println("sixtimesthreeis\(threeTimesTable[6])")
  17. //prints"sixtimesthreeis18"

2.用法

通常用来访问集合,列表或序列中的元素
    varnumberOfLegs=["spider":8,"ant":6,"cat":4]
  1. numberOfLegs["bird"]=2

3.选项

子脚本允许任意数量的参数,并且参数类型没有限制,一个类或结构体可使用多个子脚本的实现,根据传入的参数进行区分,称为子脚本的重载
    structMatrix{
  1. rows:Int,columns:Int
  2. vargrid:Double[]
  3. init(rows:Int,columns:Int){
  4. self.rows=rows
  5. self.columns=columns
  6. grid=Array(count:rows*columns,0); background-color:inherit">repeatedValue:0.0)
  7. funcindexIsValidForRow(row:Int,0); background-color:inherit">column:Int)->Bool{
  8. returnrow>=0&&row<rows&&column>=0&&column<columns
  9. subscript(row:Int,0); background-color:inherit">column:Int)->Double{
  10. assert(indexIsValidForRow(row,0); background-color:inherit">column:column),"Indexoutofrange")
  11. returngrid[(row*columns)+column]
  12. set{
  13. grid[(column]=newValue
  14. varmatrix=Matrix(rows:2,0); background-color:inherit">columns:2)
  15. matrix[0,0); background-color:inherit">1]=1.5
  16. matrix[1,0); background-color:inherit">0]=3.2
  17. letsomeValue=matrix[2,0); background-color:inherit">2]
  18. //thistriggersanassert,because[2,2]isoutsideofthematrixbounds
原文链接:https://www.f2er.com/swift/325170.html

猜你在找的Swift相关文章