Swift - Subscripts(下标)

Swift - Subscripts(下标) 首页 / Swift入门教程 / Swift - Subscripts(下标)

Subscripts下标可以访问类,结构和枚举中的集合,序列和列表的元素成员。这些下标用于在索引的帮助下存储和检索值。在someArray [index]的帮助下访问数组元素,而在Dictionary中的后续成员元素可以作为someDicitonary [key]访问。

下标声明语法

 " subscript"关键字用于定义,用户可以使用其返回类型指定单个或多个参数,Subscript下标可以具有读写属性,也可以具有只读属性,并且的存储和检索借助" getter"和" setter"属性。

subscript(index: Int) -> Int {
   get {
      //获取获取数据
   }
   set(newValue) {
      //用于写入数据
   }
}

下标声明 - 示例1

struct subexample {
   let decrementer: Int
   subscript(index: Int) -> Int {
      return decrementer/index
   }
}
let division=subexample(decrementer: 100)

print("The number is divisible by\(division[9]) times")
print("The number is divisible by\(division[2]) times")
print("The number is divisible by\(division[3]) times")
print("The number is divisible by\(division[5]) times")
print("The number is divisible by\(division[7]) times")

运行上述程序时,我们得到以下输出-

无涯教程网

The number is divisible by 11 times
The number is divisible by 50 times
The number is divisible by 33 times
The number is divisible by 20 times
The number is divisible by 14 times

下标声明 - 示例2

class daysofaweek {
   private var days=["Sunday", "Monday", "Tuesday", "Wednesday",
      "Thursday", "Friday", "saturday"]
   subscript(index: Int) -> String {
      get {
         return days[index]
      }
      set(newValue) {
         self.days[index]=newValue
      }
   }
}
var p=daysofaweek()

print(p[0])
print(p[1])
print(p[2])
print(p[3])

运行上述程序时,我们得到以下输出-

无涯教程网

Sunday
Monday
Tuesday
Wednesday

下标中的选项

Subscripts下标采用单个或多个输入参数,并且这些输入参数也属于任何数据类型,他们还可以使用变量和可变参数,Subscripts下标不能提供默认参数值或使用任何输入输出参数。

struct Matrix {
   let rows: Int, columns: Int
   var print: [Double]
   init(rows: Int, columns: Int) {
      self.rows=rows
      self.columns=columns
      print=Array(count: rows * columns, repeatedValue: 0.0)
   }
   subscript(row: Int, column: Int) -> Double {
      get {
         return print[(row * columns) + column]
      }
      set {
         print[(row * columns) + column]=newValue
      }
   }
}
var mat=Matrix(rows: 3, columns: 3)

mat[0,0]=1.0
mat[0,1]=2.0
mat[1,0]=3.0
mat[1,1]=5.0

print("\(mat[0,0])")

运行上述程序时,我们得到以下输出-

无涯教程网

1.0

Swift 4 Subscripts下标针对适当的数据类型支持单个参数到多个参数的声明,该程序将"矩阵"结构声明为2 * 2维数组矩阵,以存储"双精度"数据类型。 

矩阵的新是通过将行数和列数传递给初始化来创建的,如下所示。

链接:https://www.learnfk.comhttps://www.learnfk.com/swift/swift-subscripts.html

来源:LearnFk无涯教程网

var mat=Matrix(rows: 3, columns: 3)

可以通过将行和列值传递到Subscripts下标(以逗号分隔)来定义矩阵值,如下所示。

mat[0,0]=1.0  
mat[0,1]=2.0
mat[1,0]=3.0
mat[1,1]=5.0

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入浅出gRPC -〔李林锋〕

重学前端 -〔程劭非(winter)〕

MongoDB高手课 -〔唐建法(TJ)〕

Redis核心技术与实战 -〔蒋德钧〕

物联网开发实战 -〔郭朝斌〕

Spark性能调优实战 -〔吴磊〕

陶辉的网络协议集训班02期 -〔陶辉〕

Kubernetes入门实战课 -〔罗剑锋〕

AI绘画核心技术与实战 -〔南柯〕

好记忆不如烂笔头。留下您的足迹吧 :)