Swift下标

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

对于单个类型,下标可以是单个声明到多个声明。 可以使用适当的下标来重载传递给下标的索引值的类型。 根据用户对其输入数据类型声明的要求,下标的范围也从一维到多维。

下标声明语法及其用法

回顾一下计算属性。 下标也遵循与计算属性相同的语法。 对于查询类型实例,下标写在方括号内,后跟实例名称。 下标语法遵循与“实例方法”和“计算属性”语法相同的语法结构。 subscript关键字用于定义下标,用户可以使用返回类型指定单个或多个参数。 下标可以具有读写或只读属性,并且在gettersetter属性的帮助下存储和检索实例,如计算属性的属性。

语法

subscript(index: Int) −> Int {
   get {
      // used for subscript value declarations
   }
   set(newValue) {
      // definitions are written here
   }
}

示例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")

当使用playground运行上述程序时,得到以下结果 -

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])

当使用playground运行上述程序时,得到以下结果 -

Sunday
Monday
Tuesday
Wednesday

下标中的选项

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

定义多个下标称为“下标重载”,类或结构可根据需要提供多个下标定义。 这些多个下标是根据下标括号中声明的值的类型推断的。参考以下示例代码 -

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])")

当使用playground运行上述程序时,得到以下结果 -

1.0

Swift 4下标支持单个参数到适当数据类型的多个参数声明。 程序将Matrix结构声明为2 * 2维数组矩阵,以存储Double数据类型。 Matrix参数输入整数数据类型,用于声明行和列。

通过将行和列计数传递给初始化来创建Matrix的新实例,如下所示。

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

上一篇:Swift方法

下一篇:Swift继承

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程