八、枚舉

枚舉為一組相關(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)

6.遞歸枚舉:有一個(gè)或多個(gè)枚舉成員使用該枚舉類型的實(shí)例作為關(guān)聯(lián)值

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容