목차

  1. Subscript Syntax
  2. Subscript Usage
  3. Type Subscripts

Subscripts

 

Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence.  

 

(subscript - 컬렉션, 리스트, 시퀀스의 멤버 엘리먼트에 접근하기 위한 shortcut을 제공)

ex) someArray[index], someDictionary[key], ...

 

 

1. Subscript Syntax

- subscripts can be read-write or read-only.

subscript(index: Int) -> Int {
    get {
        // Return an appropriate subscript value here.
    }
    set(newValue) {
        // Perform a suitable setting action here.
    }
}

 

2. Subscript Usage

struct Matrix {
    let rows: Int, columns: Int
    var grid: [Double]
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        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(indexIsValid(row: row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}

 

 

3. Type Subscripts

enum Planet: Int {
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
    static subscript(n: Int) -> Planet {
        return Planet(rawValue: n)!
    }
}
let mars = Planet[4]
print(mars)

 

 

 

Ref.

https://docs.swift.org/swift-book/LanguageGuide/Subscripts.html

https://kka7.tistory.com/118?category=919617

+ Recent posts