맛동산이

스위프트 스터디 11탄) 서브스크립트(subscript) 본문

앱/Swift 문법

스위프트 스터디 11탄) 서브스크립트(subscript)

진ddang 2023. 7. 9. 02:41

 

스위프트 공식문서를 참조하였습니다.



정의

서브 스크립트란, 클래스, 구조체, 열거형에서 스크립트를 지정해서 특정 멤버 엘리먼트에 접근할수 있는 문법을 의미한다. 서브스크립트를 사용하면, 특정 메소드 없이도 값을 할당 하거나 가져올수 있다.

 

서브스크립트 문법

서브스크립트 선언 문법은 읽고-쓰기(read-write), 혹은 읽기 전용(read only) 만 가능하다. 계산된 프로퍼티(computed property)와 동일하게 , getter, setter 방식을 사용한다.

subscript(index: Int) -> Int { 	get{ } 	set(newValue) { 액션 }  }

만일 이렇게 get set을 사용하지 않고 set에 대한 인자 값을 따로 사용하지 않는다면, 자동적으로 default값을 newValue로 사용하게 된다.

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

 

서브스크립트 예시

struct TimesTable {     let multiplier: Int     subscript(index: Int) -> Int {         return multiplier * index     } } let threeTimesTable = TimesTable(multiplier: 3) print("six times three is \(threeTimesTable[6])") // "six times three is 18" 출력


Uploaded by

N2T
반응형