Swift Examples - Nested Types

The Swift Programming Language Examples

源码在 GitHub:https://github.com/gewill/The-Swift-Programming-Language-2.1-Examples

Playground ->

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// : Playground - noun: a place where people can play

import UIKit

//: 嵌套类型(Nested Types)



//嵌套让我们可以为常数生成一个命名空间(namespace)。例如:我们可以使用Constants.FoursquareApi.BaseUrl来访问Foursquare的BaseUrl常数,这样会使得数据可读性更高,并为相关的常数提供一系列封装。
//http://geek.csdn.net/news/detail/58593
import Foundation
struct Constants {
struct FoursquareApi {
static let BaseUrl = "https://api.foursquare.com/v2/"
}
struct TwitterApi {
static let BaseUrl = "https://api.twitter.com/1.1/"
}
struct Configuration {
static let UseWorkaround = true
}
}


//上面的嵌套是不错的实践,当然扑克牌作为例子是非常合适的。

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 {
var output = "suit is \(suit.rawValue),"
output += " value is \(rank.values.first)"
if let second = rank.values.second {
output += " or \(second)"
}
return output
}
}

BlackjackCard(rank: .Ace, suit: .Spades).description
let heartsSymbol = BlackjackCard.Suit.Hearts.rawValue