嵌套类型
枚举常被用于为特定类或结构体实现某些功能。类似地,也能够在某个复杂的类型中,方便地定义工具类或结构体来使用。为了实现这种功能,Swift允许你定义嵌套类型
,可以在支持的类型中定义嵌套的枚举、类和结构体。
要在一个类型中嵌套另一个类型,将嵌套类型的定义写在其外部类型的{}内,而且可以根据需要定义多级嵌套
。
嵌套类型实践
/** * 一个结构体BlackjackCard(二十一点),用来模拟BlackjackCard中的扑克牌点数。在BlackjackCard中,Ace牌的面值可以是1或者11。 */
struct BlackjackCard {
enum Suit: Character {
case Spades = "♠"
case Hearts = "♡"
case Diamonds = "♢"
case Clubs = "♣"
}
enum Rank: Int {
case Two = 2,Three,Four,Five,Six,Seven,Eight,Nine,Ten
case Jack,Queen,King,Ace
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 rank: Rank
let suit: Suit
var description: String {
var s = "\(suit.rawValue)"
s += "\(rank.values.first)"
s += rank.values.second != nil ? " or \(rank.values.second!)" : ""
return s
}
}
let ace = BlackjackCard(rank: BlackjackCard.Rank.Ace,suit: BlackjackCard.Suit.Diamonds)
print(ace) // BlackjackCard(rank: BlackjackCard.Rank.Ace,suit: BlackjackCard.Suit.Diamonds)
print(ace.description) // ♢1 or 11
引用嵌套类型
在外部引用嵌套类型时,在嵌套类型的类型名前加上其外部类型的类型名作为前缀。
/** * 一个结构体BlackjackCard(二十一点),用来模拟BlackjackCard中的扑克牌点数。在BlackjackCard中,Ace牌的面值可以是1或者11。 */
struct BlackjackCard {
enum Suit: Character {
case Spades = "♠"
case Hearts = "♡"
case Diamonds = "♢"
case Clubs = "♣"
}
enum Rank: Int {
case Two = 2,second: nil)
}
}
}
let rank: Rank
let suit: Suit
var description: String {
var s = "\(suit.rawValue)"
s += "\(rank.values.first)"
s += rank.values.second != nil ? " or \(rank.values.second!)" : ""
return s
}
}
let heartSymbol = BlackjackCard.Suit.Hearts.rawValue
print(heartSymbol) // ♡