Swift 下標(biāo)
在Swift4中,下標(biāo)是訪問列表、序列或集合元素的快捷方式。愛掏網(wǎng) - it200.com下標(biāo)用于使用索引來設(shè)置或檢索值,而不是編寫函數(shù)。愛掏網(wǎng) - it200.com
例如:
Array[Index], Dictionary[Key]
下標(biāo)可以是單個或多個類型聲明。愛掏網(wǎng) - it200.com它還根據(jù)用戶對其輸入數(shù)據(jù)類型聲明的要求,從單個維度到多個維度進(jìn)行范圍選擇。愛掏網(wǎng) - it200.com
語法
下標(biāo)的語法與計算屬性相同。愛掏網(wǎng) - it200.com對于查詢類型實例,下標(biāo)寫在方括號內(nèi),后跟實例名稱。愛掏網(wǎng) - it200.com
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
下標(biāo)重載
In Swift4,下標(biāo)可以接受單個到多個屬于任何數(shù)據(jù)類型的輸入?yún)?shù)。愛掏網(wǎng) - it200.com定義多個下標(biāo)被稱為下標(biāo)重載,其中一個類或結(jié)構(gòu)可以提供多個下標(biāo)定義。愛掏網(wǎng) - it200.com
聲明:所有內(nèi)容來自互聯(lián)網(wǎng)搜索結(jié)果,不保證100%準(zhǔn)確性,僅供參考。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進(jìn)行處理。