티스토리 뷰

클래스, 구조체 그리고 열거형에서 스크립트를 정의하여 사용할 수 있다. SubScripts란 Collection, List, Sequence 등 집합의 특정 멤버 엘리먼트에 간단하게 접근할 수 있는 문법이다.

 

SubScripts를 이용하면 추가적인 메서드 없이 특정 값을 할당하거나 가져올 수 있다. 예를들면, 배열 인스턴스의 특정 엘리먼트는 someArray[index] 문법으로, dictionary 인스턴스의 특정 엘리먼트는 someDictionary[key]로 접근할 수 있다.

 

바로 한번 알아보자.

 

1. Subscript 문법

Subscripts 선언 문법은 인스턴스 메서드와 Computed 프로퍼티를 선언하는 것과 비슷하다. 

subscript(index: Int) -> Int {
    get {
        // 적절한 반환 값
    }
    set(newValue) {
        // 적절한 set 액션
    }
}

 

마찬가지로 따로 setter를 정의하지 않으면, read-only로 선언된다.

subscript(index: Int) -> Int {
    // 적절한 반환 값
}

 

아래는 read-only로 선언한 subscripts의 예시이다.

struct TimesTable {
	let multiplier: Int
    subscript(index: Int) -> Int {
    	return multiplier * index
    }
}

let threeTimesTable = TimesTable(multiplier: 3)

print("six times three is \(threeTimesTable[6])")

2. Subscript 의 사용

 

아래 예시는 딕셔너리에서의 서브스크립트 사용 예시이다.

var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
numberOfLegs["bird"] = 2

 

서브스크립트는 입력 인자의 수에 제한이 없고, 입력 인자의 타입과 반환 타입의 제한도 없다. 아래 예제는 서브스크립트를 사용하여 다차원 행렬을 선언하고 접근하는 예시이다.

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
        }
    }
}

 

Comments