2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Subscript Options

Last updated at Posted at 2014-06-11

SwiftにはSubscriptという機能がある。
これはArrayやDictionaryに使う[]演算子をオーバロードするような機能。
Scalaでいうとapplyのようなもの。これをクラスのメソッドとして実装できるのが便利。

struct Test {
    let v: Int
    subscript(index: Int) -> Int {
        return v * index
    }
}

let t = Test(v: 3)
t[3]

このSubscriptはいくつも定義することができて、実行時に最適な型のSubscriptが呼ばれる

struct Test {
    let v: Int
    var s: String
    subscript(index: Int) -> Int {
        return v * index
    }
    subscript(prefix: String) -> String {
        return "\(prefix) \(s)"
    }
}

let t = Test(v: 3, s: "Test")
t["This is"] // 2つ目のSubscriptメソッドが呼ばれる

docにも書いてあったけど数値計算用の行列ライブラリとか作るときに便利そう。

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)
    }
    subscript(row: Int, column: Int) -> Double {
        get {
            return grid[(row * columns) + column]
        }
        set {
            grid[(row * columns) + column] = newValue
        }
    }
}

var m = Matrix(rows: 3, columns: 3)  // ここはvarにする必要がある
m[0,2] = 1.0 // 参照にはカンマ区切りでパラメタを与えられる

m[0,2]

参照:The Swift Programming Language ~Subscript~

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?