Swift-枚舉
枚舉定義了一個(gè)通用類型的一組相關(guān)的值价脾,使你可以在你的代碼中以一個(gè)安全的方式來使用這些值羽莺。
OC的枚舉寫法
typedef enum {
checkNetWorkStateUnknown = 0, // 沒有網(wǎng)絡(luò)
checkNetWorkStateReachable , // 沒有網(wǎng)絡(luò)
checkNetWorkStateViaWWAN , // 手機(jī)自帶網(wǎng)絡(luò)
checkNetWorkStateWiFi, // WIFI狀態(tài)
} NetWorkState;
*/
enum CompassPoint {
case North
case South
case East
case West
}
//Swift用Case來確認(rèn)情況區(qū)分
還可以這樣
enum Planet {
case Mercury,Venus,Earth
}
//調(diào)用(直接用點(diǎn)語法)
var directHead = CompassPoint.West
/*directionToHead的類型被推斷當(dāng)它被CompassPoint的一個(gè)可能值初始化。一旦directionToHead被聲明為一個(gè)CompassPoint猬错,你可以使用更短的點(diǎn)(.)語法將其設(shè)置為另一個(gè)CompassPoint的值:
*/
directHead = .East
* 匹配枚舉值和Switch語句
let direcrt = Planet.Mercury
switch direcrt {
case .Mercury:
print("----north")
case .Venus:
print("----West")
default:
print("------Defsult")
}
關(guān)聯(lián)值(Associated Values)
你可以定義 Swift 的枚舉存儲(chǔ)任何類型的關(guān)聯(lián)值窗看,如果需要的話,每個(gè)成員的數(shù)據(jù)類型可以是各不相同的倦炒。枚舉的這種特性跟其他語言中的可辨識(shí)聯(lián)合(discriminated unions)显沈,標(biāo)簽聯(lián)合(tagged unions),或者變體(variants)相似。
enum Barcode {
case UPDA(Int,Int,Int)
case QRCode(String)
}
// 調(diào)用
var productBarcode = Barcode.UPDA(12, 12, 34)
productBarcode = .QRCode("1345678820")
//判斷productBarcode是屬于哪一個(gè)情況
switch productBarcode {
case .UPDA(let numberSystem,let identifier,let check):
print("UPC-A with value of \(numberSystem), \(identifier), \(check).")
case .QRCode(let produceCode):
print("-----\(produceCode)")
}
/*
如果一個(gè)枚舉成員的所有關(guān)聯(lián)值被提取為常量拉讯,或者它們?nèi)勘惶崛樽兞康咏剑瑸榱撕?jiǎn)潔,你可以只放置一個(gè)var或者let標(biāo)注在成員名稱前:
*/
switch productBarcode {
case let .UPDA( numberSystem, identifier, check):
print("UPC-A with value of \(numberSystem), \(identifier), \(check).")
case let .QRCode( produceCode):
print("-----\(produceCode)")
}
原始值(Raw Values)
在關(guān)聯(lián)值小節(jié)的條形碼例子中演示了一個(gè)枚舉的成員如何聲明它們存儲(chǔ)不同類型的關(guān)聯(lián)值魔慷。作為關(guān)聯(lián)值的替代只锭,枚舉成員可以被默認(rèn)值(稱為原始值)預(yù)先填充,其中這些原始值具有相同的類型院尔。
enum NetState: Int {
case WIFI = 0, fffffff, GPRS
}
// //使用枚舉成員的rawValue方法可以訪問該枚舉成員的原始值:
NetState.WIFI.rawValue //0
NetState.fffffff.rawValue// 1
NetState.GPRS.rawValue // 2
//使用枚舉的init(rawValue: index)方法來試圖找到具有特定原始值的枚舉成員蜻展。
NetState.init(rawValue: 2)?.rawValue
NOTICE:獲取枚舉數(shù)據(jù),有可能超出數(shù)據(jù)范圍邀摆,取不出任何數(shù)據(jù)纵顾。所以是可選性用 “?”
如有問題可添加我的QQ:1290925041
還可添加QQ群:234812704(洲洲哥學(xué)院)
歡迎各位一塊學(xué)習(xí)栋盹,提高逼格施逾!
也可以添加洲洲哥的微信公眾號(hào)
更多消息
更多信iOS開發(fā)信息 請(qǐng)以關(guān)注洲洲哥 的微信公眾號(hào),不定期有干貨推送:
這里寫圖片描述