枚举常被用于为特定类或结构体实现某些功能。类似的,枚举可以方便的定义工具类或结构体,从而为某个复杂的类型所使用。为了实现这种功能,Swift 允许你定义嵌套类型,可以在支持的类型中定义嵌套的枚举、类和结构体。
要在一个类型中嵌套另一个类型,将嵌套类型的定义写在其外部类型的{}内,而且可以根据需要定义多级嵌套。
1.嵌套类型实践
struct BlackjackCard { //嵌套的Suit enum Suit : Character { case Spades = "♠"; case Hearts = "♡"; case Diamonds = "♢"; case Clubs = "♣"; } //嵌套的Rank enum Rank : Int { case Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten; case Jack, Queen, King, Ace; //嵌套结构体Values struct Values { let first: Int; let 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); } } } let suit: Suit; let rank: Rank; 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(suit: .Spades, rank: .Ace); print("theAceOfSpades: (theAceOfSpades.description)"); //"theAceOfSpades: suit is ♠, value is 1 or 11 " //在外部引用嵌套类型时,在嵌套类型的类型名前加上其外部类型的类型名作为前缀 let heartsSymbol = BlackjackCard.Suit.Hearts.rawValue;