Swift/활용

Swift subscript와 init으로 명확하고 간결한 코드 작성

박신혁 2024. 6. 25. 23:17

Box 구조체는 여러 개의 Item을 포함하고 있다

import Foundation

struct Box {
    let item: [Item]
}

struct Item {
    let name: String
}

let item1 = Item(name: "Tomica")
let item2 = Item(name: "Pokemon_Card")

let box = Box(item: [item1, item2])

print(box.item[0].name)

//출력 : Tomica

 

단순한 코드지만

밑에 값을 넣어주는것부터 출력까지 접근해줘야할게 많아 보인다

 

 

import Foundation

struct Box {
    
    let item: [Item]
	
    //subscript 정의
    subscript(_ itemIndex: Int) -> Item {
        return item[itemIndex]
    }
}

struct Item {
    let name: String

	//초기화
    init(_ name: String) {
        self.name = name
    }
}

let item1 = Item("Tomica")
let item2 = Item("Pokemon_Card")

let box = Box(item: [item1, item2])

print(box[0].name)

//출력 : Tomica

 

subscript를 정의하고 init으로 초기화하여 접근을 보다 간결하게 할 수 있다

(subscript정의 와 init(초기화)은 이 외에도 더 많은 목적을 가지고 있다)

728x90