下標
標籤
index 取值
var text = ["a", "b", "c", "d", "e"]
print(text[0])
print(text[3])
key 取值
var number = ["a": "abcde", "b": "12345"]
print(number["a"])
基本架構
範例ㄧ
subscript((名稱): (型別)) -> (返回型別) {
return (返回值)
}
class data {
var number = 100
subscript(newdata: Int) -> Int {
return number / newdata
}
}
print(DATA.number)
print(DATA[10])
範例二
subscript((名稱): (型別)) -> (返回型別) {
get {
return (返回值)
}
set{
}
}
class data {
var number = 100
subscript(newdata: String) -> Int {
get {
print(newdata)
return number * 2
}
set {
number *= newValue
}
}
}
let DATA = data()
print(DATA["data"])
DATA["data"] = 5
print(DATA.number)