美文网首页
Nested Types

Nested Types

作者: 夜雨聲煩_ | 来源:发表于2017-12-28 20:07 被阅读0次
    • 为了表示更复杂的结构,swift中类、结构体和枚举可以使用内嵌类型
    • 在结构体中嵌套枚举的复杂实例
        //Nested Types in Action
        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 properities 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)")
      
      
    • 可以直接只用类型.类型访问
      let heartSymbol = BlackJackCard.Suit.hearts.rawValue
      

    相关文章

      网友评论

          本文标题:Nested Types

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