嵌套类型(学习笔记)

  • 嵌套类型的应用
    • 示例如下

      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
          }
      }
      // BlackjackCard 内嵌套了两个枚举类型 Rank、Suit,Rank有一个更深的嵌套类型Values
      // BlackjackCard 有两个存储属性,没有显示的构造器, 由于Rank、Suit 都是其嵌套类型,所以可以推导出类型,下面可以直接(
      .ace .spades)
      let theAceOfSpades = BlackjackCard(rank: .ace, suit: .spades)
      print("theAceOfSpades: \(theAceOfSpades.description)")
      // Prints "theAceOfSpades: suit is ♠, value is 1 or 11"
  • 嵌套类型的引用
    • 示例

      let heartSymbol = BlackjackCard.Suit.hearts.rawValue
      // heartSymbol is "♡"
01-21 03:55