Skip to content

Commit 4579184

Browse files
committed
嵌套类型
1 parent 52e7740 commit 4579184

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Type Casting.playground/Contents.swift

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,55 @@ for thing in things {
126126
}
127127

128128

129+
// 嵌套类型
130+
// swift允许定义嵌套类型,可以在枚举类型、类和结构体中定义支持嵌套的类型
131+
// 要在一个类型中嵌套另一个类型,将需要嵌套的类型的定义写在被嵌套类型的区域{}内,而且可以根据需要定义多级嵌套
132+
133+
// 嵌套类型实例
134+
struct BlackjackCard {
135+
// 嵌套定义枚举类型suit
136+
enum Suit:Character {
137+
case Spades = "?"
138+
case Hearts = "!"
139+
case Diamonds = "~"
140+
case Clubs = "&"
141+
}
142+
143+
// 嵌套定义枚举Bank
144+
enum Rank:Int {
145+
case Two = 2,There,Four,Five,Six,Seven,Eight,Nine,Ten
146+
case Jack,Queen,King,Ace
147+
struct Value {
148+
let first:Int, second:Int?
149+
}
150+
var values:Value {
151+
switch self {
152+
case .Ace:
153+
return Value(first: 1, second: 11)
154+
case .Jack, .Queen, .King:
155+
return Value(first: 10, second: nil)
156+
default:
157+
return Value(first: self.rawValue, second: nil)
158+
}
159+
}
160+
}
161+
let rank:Rank, suit:Suit
162+
var description:String {
163+
var output = "suit is \(suit.rawValue)"
164+
output += "value is \(rank.values.first)"
165+
if let second = rank.values.second {
166+
output += "or \(second)"
167+
}
168+
return output
169+
}
170+
}
129171

172+
let theAceOfSpades = BlackjackCard(rank: .Ace, suit: .Spades)
173+
print("theAceOfSpades:\(theAceOfSpades.description)")
130174

175+
// 嵌套类型的引用
176+
// 在外部对嵌套类型的引用,以被嵌套类型的名字为前缀,加上所要引用的属性名
177+
let heartsSymbol = BlackjackCard.Suit.Hearts.rawValue
131178

132179

133180

0 commit comments

Comments
 (0)