Notice
Recent Posts
Recent Comments
Link
大器晩成
[Extensions] 멤버의 확장(중첩타입, Nested Types) 본문
중첩타입 (Nested Types)
class Person {
class SomeType {
}
}
- 클래스 안에 클래스나, 클래스 안에 구조체를 만들거나, 중첩적으로 만들 수 있는 타입을 중첩타입이라고 합니다.
중첩타입의 장점
- 특정 타입에서 필요한 항목에 대해서 중첩으로 내부에서만 사용이 가능하도록 할 수 있습니다.
class Day {
enum WeekDay{
case mon
case tue
case wed
}
var day: WeekDay = .mon
}
// 타입 내부에 있는 타입
var day: Day.WeekDay = Day.WeekDay.mon
- WeekDay는 Day라는 클래스 내부에서만 사용하는 열거형 타입입니다.
확장은 기존 클래스, 구조체 및 열거형에 새로운 중첩된 타입을 추가할 수 있습니다.
- Apple 공식문서 예제
// Int(정수형 타입)에 종류(Kind) ====> 중첩 열거형 추가해 보기
extension Int {
enum Kind { // 음수인지, 0인지, 양수인지
case negative, zero, positive
}
var kind: Kind { // 계산 속성으로 구현
switch self { // self 정수형의 인스턴스
case 0: // 0인 경우
return Kind.zero
case let x where x > 0: // 0보다 큰경우
return Kind.positive
default: // 나머지 (0보다 작은 경우)
return Kind.negative
}
}
}
let a = 1
a.kind // 숫자 1의 (인스턴스) 계산속성을 호출 ====> 해당하는 열거형(Int.Kind타입)을 리턴
let b = 0
b.kind // b.kind == 0.kind
let c = -1
c.kind
//Int.Kind //타입만 나타낸것
Int.Kind.positive
Int.Kind.zero
Int.Kind.negative
var f = Int.Kind.positive //변수에 대입도 가능
let d: Int.Kind = Int.Kind.negative //타입 명시
// 위의 확장을 통해서, 어떤 Int값에서도 중첩 열거형이 쓰일 수 있음
// 위의 확장을 활용한 ===> 함수 만들어보기
func printIntegerKinds(_ numbers: [Int]) {
for number in numbers {
switch number.kind {
case .negative:
print("- ", terminator: "")
case .zero:
print("0 ", terminator: "")
case .positive:
print("+ ", terminator: "")
}
}
print("")
}
// 함수 실행해보기
printIntegerKinds([3, 19, -27, 0, -6, 0, 7]) // + + - 0 - 0 +
728x90
'iOS > Swift 문법' 카테고리의 다른 글
[Protocols] 프로토콜 요구사항 (0) | 2025.01.12 |
---|---|
[Protocols] 프로토콜(Protocol) (0) | 2025.01.09 |
[Extensions] 멤버의 확장(서브 스크립트) (0) | 2025.01.05 |
[Extensions] 생성자의 확장 (0) | 2024.12.26 |
[Extensions] 멤버의 확장(메서드) (0) | 2024.12.23 |