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