サブスクリプトは入力パラメータをいくつでも取ることができ、入力パラメータの型も問いません。また、サブスクリプトはどのような型でも返すことができます。サブスクリプトは変数パラメータや可変数パラメータにすることができますが、入出力パラメータにすることやパラメータのデフォルト値を付けることはできません。
クラスや構造体は必要なだけサブスクリプトの実装を持つことができ、利用される適切なサブスクリプトは、使用時にサブスクリプトの角括弧内にある値の型をもとに推論されます。複数のサブスクリプトの定義をサブスクリプトオーバーロードと呼びます。
パラメータが 1 つのサブスクリプトが最も一般的ですが、型に適している場合には、複数のパラメータを取るサブスクリプトを定義することもできます。次の例では、Double
値の 2 次元マトリックスを表現する構造体 Matrix
を定義しています。構造体 Matrix
のサブスクリプトは整数パラメータを 2 つ取ります。
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) + column] = newValue
}
}
}
Matrix
には 2 つのパラメータ rows
と columns
を取るイニシャライザがあり、Double
型の rows * columns
値を保管するのに十分な大きさの配列を生成します。マトリックスの各ポジションは初期値の 0.0
になります。配列のサイズとセルの初期値 0.0
がイニシャライザに渡されて、正しいサイズの新しい配列を初期化します。このイニシャライザは Creating an Array with a Default Value で詳細に説明されています。
適切な行と列の数をイニシャライザに渡して新しい Matrix
インスタンスを構築することができます。
var matrix = Matrix(rows: 2, columns: 2)
この例では、2 行と 2 列の新しい Matrix
インスタンスを生成しています。この Matrix
インスタンスの grid
配列は、左上から右下の順でマトリックスをフラットにしたバージョンです。
行と列の値をカンマ区切りでサブスクリプトに渡して、マトリックスの値を設定することができます。
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2
この 2 文は、マトリックスの右上(row
が 0
で column
が 1
)のポジションに 1.5
を設定し、左下(row
が 1
で column
が 0
)のポジションに 3.2
を設定するサブスクリプトの setter を呼び出しています。
Matrix
サブスクリプトの getter と setter は共に、サブスクリプトの row
と column
値が有効であることをチェックするアサーションを含んでいます。アサーションを助けるために、Matrix
はリクエストされた row
と column
がマトリックスの範囲内かどうかチェックする便利なメソッド indexIsValidForRow(_:column:)
を含んでいます。
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
マトリックス範囲外のサブスクリプトにアクセスしようとした場合、アサーションが作動します。
let someValue = matrix[2, 2]
// [2, 2] はマトリックスの範囲外であり、アサートを作動
Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.