swift 嵌套类型

2023-11-22 09:15:11 浏览数 (1)

嵌套类型实践示例官方demo

代码语言:javascript复制
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
    }
}

引用嵌套类型

代码语言:javascript复制
let heartsSymbol = BlackjackCard.Suit.hearts.rawValue    //♡

0 人点赞