Swift4语法极简手册 — Nested Types

Swift4语法极简手册

第二十章节:Nested Types

Nested Types

Swift中,type可以嵌套定义在另一个Type中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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)
}
}
}
let rank: Rank, suit: Suit
}
let theAceOfSpades = BlackjackCard(rank: .ace, suit: .spades)

访问嵌套的类的方式

1
let heartsSymbol = BlackjackCard.Suit.hearts.rawValue