Swift系列8-枚举

枚举

枚举可以是任何类型,如整型,浮点型等
枚举没有标明类型时,它就是一个新的类型;也就说,定义一个枚举,就是一个新的类型.
使用enum关键字进行定义枚举

定义枚举

样式1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
enum SeasonState {
case spring
case summer
case autumn
case winter
}
//使用switch来匹配枚举
var arr = [SeasonState]()
arr = [.spring,.summer,.autumn,.winter]
let season:SeasonState = arr[Int(arc4random()) % arr.count]
switch season {
case .winter:
print("It is winter")
default:
print("no case ")
}

样式2

多个值可以在同一行表示,用逗号隔开

1
2
3
enum WeatherState {
case cold,hot,wind
}

样式3

遍历枚举:使用CaseIterable关键字修饰可以对枚举进行遍历

1
2
3
4
5
6
7
8
enum Day:CaseIterable {
case day1,day2,day3,day4
}
//遍历
let days = Day.allCases
for day in days {
print("day: \(day)")
}

样式4

原始值,首个枚举赋值1,后面的值会依次递增赋值

1
2
3
4
enum week :Int{
case w1 = 1,w2,w3,w4,w5,w6,w7
}
//w2 = 2,以此类推

样式5

定义关联值的枚举

1
2
3
4
5
6
enum Barcode {
case upc(Int,Int,Int)
case qrCode(String)
}
//使用关联值枚举,可以在每次生成不同的值
let b1:Barcode = Barcode.upc(100, 200, 300);print(b1)

The End