Apple-CS-interview / iOS-CS-interview

7 stars 0 forks source link

Subscripts에 대해 설명하시오. #8

Open vichye-1 opened 1 year ago

ronick-grammer commented 1 year ago

Subscripts란

class, struct 그리고 enum 타입에서 배열의 인덱스처럼 데이터의 특정 요소에 접근할 수 있도록 해주는 Swift의 문법이다.

Subscript의 기본 형태

Array와 Dictionary

Swift의 데이터 타입인 ArrayDictionary도 인덱스를 통해 값을 할당/접근 할때, Subscript를 사용한다는 것을 유추해볼 수 있다.

nums[0] // 1 nums[1] // 2


- **Dictionary**
```swift
let dict: [String: Int] = ["one": 1, "two": 2]

dict["one"]             // 1
dict["two"]             // 2

Subscript 옵션

Subscript는 일반적인 메서드처럼 제공하는 옵션들이 있다.

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

    // 함수 오버로딩 with Default Value
    subscript(exampleIndex: Int = 1) -> Int {
        return exampleIndex + 2
    }
}

var matrix = Matrix(rows: 2, columns: 2)

matrix[0, 1] = 1.5
matrix[1, 0] = 3.2
matrix[]     // "3"
matrix[3]   // "5"

📝 참고 사이트

vichye-1 commented 1 year ago

Subscript의 정의

collection의 요소에 접근할 수 있으며, 클래스, 구조체, 열거형에서 사용할 수 있다.

someArray[index]로 Array의 인덱스에 접근할 수 있으며, someDictionary[Key]로 Dictionary의 Value에 접근할 수 있다.

Subscript 문법

서브스크립트가 구현된 문법은 계산 프로퍼티의 구문과 비슷하게 getter와 setter로 동작된다.

subscript(index: Int) -> Int {
    get {
        // Return an appropriate subscript value here.
    }
    set(newValue) {
        // Perform a suitable setting action here.
    }
}
Do-hyun-Kim commented 1 year ago

Subscripts에 대해 설명하시오.

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

Static 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)

📝 참고 사이트