swift

swift - Method and Subscript #3 (Subscript)

행복하게사는게꿈 2021. 1. 12. 12:20

let list = ["A", "B", "C"]
list[0]

// 이런게 바로 Subscript

// Subscript 직접 구현
// parameter에 제한은 없지만 두개 이하로 보통 선언
// 입출력 파라미터 선언 불가능
// 파라미터 생략 불가능

// returnType은 subscript에서 중요 : subscript를 통해 리턴되는 형식인 동시에 저장하는 값의 형식임 -> 생략불가능
// get, set 블록은 computed와 동일

class List {
    var data = [1, 2, 3]
    
    func aa() {
        print(data[1])
    }
    subscript(index: Int) -> Int {
        get {
            return data[index]
        }
        set {
            data[index] = newValue
        }
    }
}

let l = List()
l[2]
l.data[1]
l.aa()

// 굳이 Subscript를 직접 선언해서 쓰는 이유가 있나..?
//l[2]
//l.data[1]
// 딱 요고 차인데

struct Matrix {
    var data = [[1,2,3], [4,5,6], [7,8,9]]
    
    subscript(row: Int, col: Int) -> Int {
        return data[row][col]
    }
}

let m = Matrix()
m[0, 2]

var data = [[1,2,3], [4,5,6], [7,8,9]]
data
type(of: data)