티스토리 뷰

출처

http://kka7.tistory.com/25


중첩된 타입 (Nested Types)

열거형은 종종 특정 클래스나 구조체의 기능을 지원하기 위해 만들어진다.
보다 복잡한 context 에서 사용하기 위해
유틸리티 클래스와 구조체를 정의하는 것이 편리할 수 있다.

열거형, 클래스, 구조체로 중첩된 타입으로 정의하는 것이 가능하다.



중첩 타입에서의 동작

아래 예제는 아래와 같은 구조를 가지고있다.

struct BlackjackCard {
enum Suit { }
enum Rank {
struct Values { }
}
}

Values 와 BlackjackCard 는 사용자 정의 초기화가 없는 구조체이기 때문에
암시적으로 멤버단위 초기화를 가진다.



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 theAceOfSpades = BlackjackCard(rank: .ace, suit: .spades)

print("theAceOfSpades: \(theAceOfSpades.description)")

// Prints "theAceOfSpades: suit is , value is 1 or 11"


let heartsSymbol = BlackjackCard.Suit.hearts.rawValue

// heartsSymbol is ""




일반적으로 정의된 컨텍스트 밖에서 중첩된 타입을 사용하려면
이름 앞에 중첩된 타입의 이름을 접두사로 붙여준다.

위 예제의 경우 context 에 의해 자연스럽게 어울리기 때문에
고의적으로 짧게 유지하기 위해 Suit, Rank, Values 의 이름을 사용했다.




공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함