# Swift 4下标用法示例

``Array[Index], Dictionary[Key]``

### 句法：

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

### 例：

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

``````Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday``````

## 下标重载

### 觉得文章有用就打赏一下文章作者

#### 微信扫一扫打赏 • 回顶