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