在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中, 下标可以接受属于任何数据类型的单个到多个输入参数。定义多个下标称为下标重载, 其中一个类或结构可以提供多个下标定义。
推荐阅读
- Swift反初始化介绍和用法
- Swift中的继承介绍和使用示例
- Swift 4方法介绍和用法详细示例
- 笔记本声音小怎样办,本文教您笔记本电脑声音小怎样办
- win10传奇花屏,本文教您win10玩传奇出现花屏怎样办
- IE修好专家_本文教您IE浏览器修好专家
- 运用激活工具如何激活win7,本文教您激活工具激活win7
- 固态硬盘装系统,本文教您固态硬盘如何装系统
- office2007激活,本文教您如何激活office2007