Fork me on GitHub

以撸代码的形式学习Swift-20:嵌套类型(Nested Types)

1 🌰

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
31
32
33
34
35
36
37
38
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 { // 用来反映Ace的两个数值()
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 theAceOfSpades = BlackjackCard(rank: .ace, suit: .spades)
print("theAceOfSpades: \(theAceOfSpades.description)")

2 引用嵌套类型

let heartsSymbol = BlackjackCard.Suit.hearts.rawValue

playground文件在andyRon/LearnSwift

坚持原创技术分享,您的支持将鼓励我继续创作!
  • 本文标题: 以撸代码的形式学习Swift-20:嵌套类型(Nested Types)
  • 本文作者: AndyRon
  • 发布时间: 2017年07月10日 - 13:44
  • 最后更新: 2018年10月15日 - 18:37
  • 本文链接: http://andyron.com/2017/swift-20-nested-types.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!