본문 바로가기

Swift Language

Swift Language - 18 - 중첩 타입 (Nested Types)

중첩 타입의 사용

/* 다음 코드는 블랙잭 게임에서 사용되는 카드를 모델링한 BlackjackCard라는 구조체를 정의한 (예)입니다. 
BlackjackCard 구조체는 Suit과 Rank라고 부르는 두개의 중첩 열거 타입을 포함 합니다. */
struct BlackjackCard {

     // nested Suit enumeration
       // struct 안에 enum이 들어갈 수 있습니다.
     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 { // enum안에 struct가 들어가는 것도 가능합니다.
             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 theAceOfSpades = BlackjackCard(rank: .ace, suit: .spades)
print("theAceOfSpades: \(theAceOfSpades.description)")
// Prints "theAceOfSpades: suit is ♠, value is 1 or 11"

 

중첩 타입의 언급 (Referring to Nested Types)

// 중첩 타입을 선언 밖에서 사용하려면 선언된 곳의 시작부터 끝까지 적어줘야 합니다.
let heartsSymbol = BlackjackCard.Suit.hearts.rawValue
// heartsSymbol is "♡"

 

 

 

출처 https://jusung.gitbook.io/the-swift-language-guide/language-guide/19-nested-types