Swift 下标

Swift 下标

在Swift4中,下标是访问列表、序列或集合元素的快捷方式。下标用于使用索引来设置或检索值,而不是编写函数。

例如:

Array[Index], Dictionary[Key] 

下标可以是单个或多个类型声明。它还根据用户对其输入数据类型声明的要求,从单个维度到多个维度进行范围选择。

语法

下标的语法与计算属性相同。对于查询类型实例,下标写在方括号内,后跟实例名称。

subscript(index: Int) ?> Int {
   get {
      // Declare subscript value here
   }
   set(newValue) {
      // Write the definitions here
   }
}

示例1

struct subscriptexample {
   let decrementer: Int
   subscript(index: Int) -> Int {
      return decrementer / index
   }
}
let division = subscriptexample(decrementer: 100)
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[4]) times")
print("The number is divisible by \(division[5]) times")
print("The number is divisible by \(division[6]) times") 

输出:

The number is divisible by 50 times
The number is divisible by 33 times
The number is divisible by 25 times
The number is divisible by 20 times
The number is divisible by 16 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])
print(p[4])
print(p[5])
print(p[6])

输出:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

下标重载

In Swift4,下标可以接受单个到多个属于任何数据类型的输入参数。定义多个下标被称为下标重载,其中一个类或结构可以提供多个下标定义。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程