/**
1.附屬腳本語法
2.附屬腳本用法
3.附屬腳本選項
*/
//附屬腳本
/**
附屬腳本可以定義在類、結構體和枚舉這些目標中,可以認爲是訪問對象、集合或序列的快捷方式,不需要再調用實例的特定的賦值和訪問方法。
對於同一個目標可以定義多個附屬腳本,通過索引值類型的不同來進行重載,並且索引值的個數可以是多個
*/
//附屬腳本語法
/**
附屬腳本允許通過在實例後面的方括號中傳入一個或多個的索引值來對實例進行訪問和賦值。
語法類似於實例方法和計算型屬性的混合
與定義實例方法類似,定義附屬腳本使用subscript關鍵字,顯式聲明入參(一個或多個)和返回類型。
與實例方法不同的是附屬腳本可以設定爲讀寫或只讀,有點像計算型的getter和setter
subscript(index: Int) -> Int {
get {
// 返回與入參匹配的Int類型的值
}
set(newValue) {
// 執行賦值操作
}
}
newValue的類型必須和附屬腳本定義的返回類型相同。與計算型屬性相同的是set的入參聲明newValue就算不寫,在set代碼塊中依然可以使用默認的newValue這個變量來訪問新賦的值。
subscript(index: Int) -> Int {
// 返回與入參匹配的Int類型的值
}
*/
struct TimesTable {
let multiplier: Int;
subscript(index: Int) -> Int {
return multiplier * index;
}
}
let threeTimesTable = TimesTable(multiplier: 3);
print("3的6倍是\(threeTimesTable[6])");
//附屬腳本用法
/**
類似字典,數組
*/
//附屬腳本選項
/**
附屬腳本允許任意數量的入參索引
*/
//二維矩陣
struct Matrix {
let rows: Int, columns: Int;
var grid = [Double]();
init(rows: Int, columns: Int) {
self.rows = rows;
self.columns = columns;
grid = Array(count: rows * columns, repeatedValue: 0.0);
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns;
}
subscript(row: Int, column: Int) -> Double {
get{
assert(indexIsValidForRow(row, column: column), "index out of range");
return grid[(row * columns) + column];
}
set {
assert(indexIsValidForRow(row, column: column), "index out of range");
grid[(row * columns) + columns] = newValue;
}
}
}
var matrix = Matrix(rows: 2, columns: 2);
let someValue = matrix[2,2];