# Swift 下標

## 語法

subscript(index:Int)->Int{get{// used for subscript value declarations}set(newValue){// definitions are written here}}

## 示例1

struct subexample {let decrementer:Int subscript(index:Int)->Int{return decrementer / index }}let division = subexample(decrementer:100) println("The number is divisible by \(division[9]) times") println("The number is divisible by \(division[2]) times") println("The number is divisible by \(division[3]) times") println("The number is divisible by \(division[5]) times") println("The number is divisible by \(division[7]) times")

The number is divisible by 11 times
The number is divisible by 50 times
The number is divisible by 33 times
The number is divisible by 20 times
The number is divisible by 14 times

## 示例2

class daysofaweek {privatevar 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() println(p[0]) println(p[1]) println(p[2]) println(p[3])

Sunday
Monday
Tuesday
Wednesday

## 下標選項

structMatrix{let rows:Int, columns:Intvarprint:[Double] init(rows:Int, columns:Int){self.rows = rows self.columns = columns print=Array(count: rows * columns, repeatedValue:0.0)} subscript(row:Int, column:Int)->Double{get{returnprint[(row * columns)+ column]}set{print[(row * columns)+ column]= newValue }}}var mat =Matrix(rows:3, columns:3) mat[0,0]=1.0 mat[0,1]=2.0 mat[1,0]=3.0 mat[1,1]=5.0 println("\(mat[0,0])") println("\(mat[0,1])") println("\(mat[1,0])") println("\(mat[1,1])")

1.0
2.0
3.0
5.0

Swift 下標支持單參數到多參數聲明相應數據類型。該程序聲明的「矩陣」結構爲2*2維數組矩陣來存儲 「Double」 數據類型。 矩陣參數被輸入整數數據類型用來聲明行和列。

var mat = Matrix(rows: 3, columns: 3)

mat[0,0] = 1.0
mat[0,1] = 2.0
mat[1,0] = 3.0
mat[1,1] = 5.0