1. 在一个类型的大挂号{}里定义里一个类型,叫做类型嵌套。Swift允许多级嵌套。
举例,下面代码用于实现21点(Blackjack
),BlackjackCard 结构体包含了 Suit 和 Rank 两个嵌套类型
:
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 { // Computed 属性 var output = "suit is (suit.rawValue)," output += " value is (rank.values.first)" if let second = rank.values.second { output += " or (second)" } return output } }
因为BlackjackCard 没有自定义的构造器,所以编译器提供隐含的成员逐个初始化构造器 memberwise initializer:
let theAceOfSpades = BlackjackCard(rank: .Ace, suit: .Spades) println("theAceOfSpades: (theAceOfSpades.description)") // prints "theAceOfSpades: suit is ♠, value is 1 or 11"
可以这样访问嵌套类型:
let heartsSymbol = BlackjackCard.Suit.Hearts.rawValue // heartsSymbol is "♡"