嵌套类型
Opened this issue · 0 comments
LeeSen11 commented
枚举通常用于为特定的类或者结构体提供一些辅助功能。同样的,在一个更加复杂的类型上下文中定义类和结构体也是非常方便的。为此,Swift允许我们定义嵌套类型,从而在它们支持的类型的定义内定义嵌套的枚举,类及结构体。
为了在某个类型里面嵌套另一种类型,在这个类型的括号里面编写其定义。类型可以根据我们的需要嵌套多个层级。
嵌套类型的实际使用
下面的代码定义了一个叫做BlackjackCard的结构体,它包含两个嵌套的枚举类型Suit和Rank:
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
}
}
引用嵌套类型
为了在嵌套类型定义的上下文之外使用,需要在其类型名称前面加上对其嵌套的类型前缀:
let heartsSymbol = BlackjackCard.Suit.hearts.rawValue
// heartsSymbol is "♡"