- 枚舉的簡單使用
- 枚舉,結構體,類的名字要大寫
- 它的名字能夠被推斷,因此第二次賦值時候之間能夠省略枚舉的名字。
enum Direction {
case north
case south
case east
case west
}
var direction = Direction.north
direction = .east
複製代碼
- 關聯值枚舉
enum Barcode {
case upc(Int, Int, Int)
case qrCode(String)
}
var aBarcode = Barcode.upc(1,2,3)
aBarcode = .qrCode("afdsagfadsfd")
switch aBarcode {
case let .upc(a, b, c):
print("a:\(a) b:\(b) c:\(c)")
case let .qrCode(str):
print(str)
}
複製代碼
- 原始值
- 原始值就是一開始定義時候要進行賦值
- 原始值有賦值,因此必須寫明類型
- 原始值是不會變的,而關聯值是之後能夠改變的。
enum ASCIICode: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
var a = ASCIICode.tab
a = .lineFeed
switch a {
case .tab:
print("tab")
case .lineFeed:
print("lineFeed")
case .carriageReturn:
print("carriageReturn")
}
複製代碼
- 原始值的隱式賦值
enum Num: Int {
case a = 1,b,c,d,e,f,g
}
enum Direction: String {
case north, south, east, west
}
print(Num.c.rawValue)
print(Direction.east.rawValue)
複製代碼
- 經過原始值查找枚舉項
enum Num: Int {
case a = 1,b,c,d,e,f,g
}
enum Direction: String {
case north, south, east, west
}
if let a = Num(rawValue: 10) {
print(a)
}else{
print("nil")
}
複製代碼
- 遞歸枚舉
遞歸枚舉要在enum前邊寫上indirect
indirect enum express {
case num(Int)
case add(express, express)
case multi(express, express)
}
func getValue(exp: express) -> Int{
switch exp {
case let .num(a):
print("1-------")
return a
case let .add(a, b):
print("2-------")
return getValue(exp: a) + getValue(exp: b)
case let .multi(a, b):
print("3-------")
return getValue(exp: a) * getValue(exp: b)
}
}
var temp = express.num(4)
print("temp = \(temp)")
var temp1 = express.num(5)
print("temp1 = \(temp1)")
var sum = express.add(temp, temp1)
print("sum = \(sum)")
var value = express.multi(sum, express.num(3))
print("value = \(value)")
print(getValue(exp: value))
複製代碼
- 枚舉的原始值類型
- 支持整數型(Int),小數型(Float,Double)字串類型(String)字符型(Character),默認是Int類型。
- 其中Int,Float,Double,String類型都支持自動賦原始值。可是字符型(Character)不支持。
//字符串型原始值(自動賦原始值)
enum test: String {
case tab
case lineFeed
case carriageReturn
case t
}
var a = test.t
print("自動賦值 字符串型原始值:\(a)---\(a.rawValue)")
//整形原始值(自動賦原始值)
enum test1: Int {
case tab
case lineFeed
case carriageReturn
case t
}
var b = test1.t
print("自動賦值 整型原始值:\(b)---\(b.rawValue)")
//小數原始值 (自動賦值)
enum test2: Float {
case tab
case lineFeed
case carriageReturn
case t
}
var c = test2.t
print("自動賦值 整型原始值:\(c)---\(c.rawValue)")
//字符原始值 (不能自動賦值!)
enum test3: Character {
case a = "a"
case b = "b"
case c = "c"
case t = "t"
}
var d = test3.t
print("自動賦值 整型原始值:\(d)---\(d.rawValue)")
複製代碼