swift 공식 문서
[iOS - swift 공식 문서] 19. Nested Type (중첩 타입)
jake-kim
2021. 7. 17. 22:38
Nested Types
- 유형의 정의 내에서 enum, class, struct를 중첩하여, 순수한 타입으로 한번더 타입으로 정의하는 것
- 예시
- Suit: 네 개의 일반적인 게임 카드 설명
- Rank: 대부분의 카드는 한가지의 값을 갖지만 에이스 카드에는 두 개의 값이 있다는 것을 표현
struct BlackjackCard {
// nested Suit enumeration
enum Suit: Character {
case spades = "♠", hearts = "♡", diamonds = "♢", clubs = "♣"
}
// nested Rank enumeration
enum Rank: Int {
case two = 2, three, four, five, six, seven, eight, nine, ten
case jack, queen, king, ace
struct Values {
let first: Int, second: Int?
}
var values: Values {
switch self {
case .ace:
return Values(first: 1, second: 11)
case .jack, .queen, .king:
return Values(first: 10, second: nil)
default:
return Values(first: self.rawValue, second: nil)
}
}
}
// BlackjackCard properties and methods
let rank: Rank, suit: Suit
var description: String {
var output = "suit is \(suit.rawValue),"
output += " value is \(rank.values.first)"
if let second = rank.values.second {
output += " or \(second)"
}
return output
}
}
- 중첩 유형 참조: 해당 이름에 중첩된 타이브이 이름을 접두사로 붙여서 참조
let heartsSymbol = BlackjackCard.Suit.hearts.rawValue
// heartsSymbol is "♡"
* 출처
https://docs.swift.org/swift-book/LanguageGuide/NestedTypes.html