《浅入浅出Swift》NestedTypes 嵌套类型

NestedTypes

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

struct BlackjackCard{
//nested Suit enumeration 嵌套适合的枚举
enum Suit: Character{//性格品质
case Spades = "♠", Hearts = "♡", Diamonds = "♢", 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, 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:
//使用toRaw 和fromRaw 两个函数,实现原始值和枚举值之间进行切换
//定义原始枚举类型是Int型,只需要给第一个定义枚举赋值,后续会顺序分配;
//你也可以使用浮点型和String类型作为枚举的原始类型
return Values(first: self.toRaw(), second: nil)
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    
//BlackjackCard properties and methods
let rank: Rank , suit: Suit
//描述
var description: String {
var output = "suit is \(suit.toRaw()),"//传入Spades
output += "value is \(rank.values.second)"

if let second = rank.values.second{
output += " or \(second)"
}
return output
}

}

let theAceOfSpades = BlackjackCard(rank: .Ace, suit: .Spades)
println("theAceOfSpades: \(theAceOfSpades.description)")
//theAceOfSpades : suit is ♠,value is lor 11

let heartsSymbol = BlackjackCard.Suit.Hearts.toRaw()//转化成实际值,
println("heartsSymbol = \(heartsSymbol)")

Reference

坚持原创技术分享,您的支持将鼓励我继续创作!
0%