Swift 4下标用法示例

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

Array[Index], Dictionary[Key]

下标可以是单个或多个类型声明。根据用户对其输入数据类型声明的要求, 它的范围也从一维到多维。
句法:
下标的语法与计算的属性相同。对于查询类型实例, 下标被写在方括号内, 后跟实例名称。
subscript(index: Int) ?> Int {get {// Declare subscript value here}set(newValue) {// Write the definitions here}}

例:
struct subscriptexample {let decrementer: Intsubscript(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 timesThe number is divisible by 33 timesThe number is divisible by 25 timesThe number is divisible by 20 timesThe 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])

输出
SundayMondayTuesdayWednesdayThursdayFridaySaturday

下标重载【Swift 4下标用法示例】在Swift4中, 下标可以接受属于任何数据类型的单个到多个输入参数。定义多个下标称为下标重载, 其中一个类或结构可以提供多个下标定义。

    推荐阅读