美文网首页swift学习笔记
第二十章 嵌套类型

第二十章 嵌套类型

作者: 运柱 | 来源:发表于2017-07-20 20:47 被阅读0次

    struct BlackjackCard {

       // 嵌套的 Suit 枚举

        enum Suit: Character {

            case Spades = "♠", Hearts = "♡", Diamonds = "♢", Clubs = "♣"

        }

        // 嵌套的 Rank 枚举

        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 的属性和方法

        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("the ace of spades: \(theAceOfSpades.description)")

    let theQueenOfClubs = BlackjackCard(rank: .Queen, suit: .Clubs)

    print("the queen of clubs: \(theQueenOfClubs.description)")

    let heartsSymbol = BlackjackCard.Suit.Hearts.rawValue

    print(BlackjackCard.Rank.init(rawValue: 14)?.values)

    相关文章

      网友评论

        本文标题:第二十章 嵌套类型

        本文链接:https://www.haomeiwen.com/subject/wjbjkxtx.html