Skip to content

Latest commit

 

History

History
58 lines (47 loc) · 2.2 KB

16.0 - Nested Types.md

File metadata and controls

58 lines (47 loc) · 2.2 KB

You can nest types in Swift. This can be useful when you only need a particular structure, class or enum in the context of a particular type.

To nest a type within another type, write its definition within the outer braces of the type it supports. Types can be nested to as many levels as are required.

For example, the following class defined playing cards in the context of blackjack:

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
    }
}

You can refer to a nested context outside of its definition context using . syntax:

let heartsSymbol = BlackjackCard.Suit.hearts.rawValue
// heartsSymbol is "♡"

For the example above, this enables the names of Suit, Rank, and Values to be kept deliberately short, because their names are naturally qualified by the context in which they are defined.

Previous Section | Back To Contents | Next Section