枚舉為一組相關(guān)的值定義了任意類型的關(guān)聯(lián)值存儲(chǔ)到枚舉成員中。
1.定義和創(chuàng)建
用case表示不同的枚舉值,同一行枚舉用“,”隔開(kāi)
enum 枚舉類型 {
case 枚舉值1
case 枚舉值2,枚舉值3
}
//.Spring的默認(rèn)值為spring
enum Seasons {
case Spring,Summer,Sutumn,Sinter
}
let currentSeason : Seasons = Seasons.Summer
print(currentSeason); //summer
2.枚舉匹配
switch currentSeason{
case .Spring:
print("123")
default:
print("this is not Spring").
} //this is not Spring
3.關(guān)聯(lián)值
//當(dāng)檢測(cè)不同的類型的時(shí)候,在case的分支代碼中提取每個(gè)關(guān)聯(lián)值作為一個(gè)常量
(用let前綴)或者作為一個(gè)變量(用var前綴)來(lái)使用:
enum Barcode {
case upc(Int,Int,Int,Int)
case qrCode(String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
switch productBarcode {
case .upc(let num1,let num2,let num3,let num4):
print("upc")
case .qrCode(let num):
print("qrCode")
}
//upc
4.原始值(默認(rèn)值)
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
5.原始值的隱式賦值
當(dāng)枚舉定義為整數(shù)時(shí),第一個(gè)枚舉成員默認(rèn)為0;當(dāng)?shù)谝粋€(gè)枚舉成員為1時(shí),后面依次
+1;
通過(guò)rawValue來(lái)獲取枚舉成員的值 或 訪問(wèn)枚舉成員;
enum tempType :Int{
case table,table2,table3
}
print(tempType.table) //table
print(tempType.table2.rawValue) //1
//初始化枚舉實(shí)例,返回類型為可選類型
let possibleType = tempType(rawValue: 2)