Subscript๋ Swift์ ์๋ ์๋ก์ด ๋ฌธ๋ฒ์ด๋ค. ๊ฐ ์ ๊ทผ์ ์์ด์ ์๋ฏธ์๋ ์ ๊ทผ ๋ฐฉ๋ฒ์ ์ ์ํ์ฌ ์ฌ์ฉํ ์ ์๋ค. ์๋ฅผ ๋ค์ด ํ๋ ฌ์ด ์์ ์ ์๋ค. ํ๋ ฌ์ด๋ผ๋ ์๋ฃ๊ตฌ์กฐ๋ฅผ ๋ง๋ค๊ณ , ์ค์ 2์ฐจ์ ๋ฐฐ์ด์ ์ ๊ทผํ๋ ๊ฒ์ฒ๋ผ ์ ๊ทผํ๊ธฐ ์ํด ์ ๊ทผ ๋ฐฉ๋ฒ์ customizingํ๋ ๊ฒ์ด๋ผ ์๊ฐํ๋ฉด ๋๊ฒ ๋ค.
Subscript
- class, struct, enum์ ์ถ๊ฐ ๊ฐ๋ฅ
- ๊ฐ๋จํ ๋ฐฉ๋ฒ์ผ๋ก member element์ ์ ๊ทผํ ์ ์๋ ๋ฐฉ๋ฒ
- ํ๋์ type์ ์ฌ๋ฌ๊ฐ์ subscript ์ฌ์ฉ ๊ฐ๋ฅ
- subscript ํ๋์ ์ฌ๋ฌ๊ฐ์ parameter ์ฌ์ฉ ๊ฐ๋ฅ
- ์์
struct Matrix { let rows: Int, columns: Int var grid: [Double] init(rows: Int, columns: Int) { self.rows = rows self.columns = columns self.grid = Array(repeating: 0.0, count: rows * columns) } func indexIsValid(row: Int, column: Int) -> Bool { return row >= 0 && row < rows && column >= 0 && column < columns } subscript(row: Int, column: Int) -> Double { get { assert(self.indexIsValid(row: row, column: column), "Index out of range") return grid[(row * self.columns) + column] } set { assert(self.indexIsValid(row: row, column: column), "Index out of range") grid[(row * self.columns) + column] = newValue } } } var A = Matrix(rows: 3, columns: 4) print(A[2, 3]) // 0.0