An enumeration is a list of related values that define a common type and let you work with values in a type-safe way.
枚舉是定義一個(gè)公共類型的相關(guān)值的列表鹰溜,可讓您以類型安全的方式使用值虽填。
聲明枚舉
enum Month {
case january
case february
case march
case april
case may
case june
case july
case august
case september
case october
case november
case december
}
enum Month {
case january, february, march, april, may, june, july, august,
september, october, november, december
}
聲明帶有計(jì)算屬性的枚舉
enum Month {
case january, february, march, april, may, june, july, august,
september, october, november, december
//let semester = month.semester // "Autumn"
var semester : String {
switch self {
case .august, .september, .october, .november, .december:
return "Autumn"
case .january, .february, .march, .april, .may:
return "Spring"
case .june, .july:
return "Summer"
}
}
}
var month = Month.april
month = .september
let semester = month.semester // "Autumn"
Raw values
Unlike enumeration values in C, Swift enum values are not backed by integers as a default.
與C中的枚舉值不同,Swift枚舉值默認(rèn)不支持整數(shù)曹动。
需要手動(dòng)設(shè)定
enum Month: Int {
case january = 1, february, march, april, may, june, july,
august, september, october, november, december
}
Month.october.rawValue // 10
Initializing with the raw value
let fifthMonth = Month(rawValue: 5)
monthsUntilWinterBreak(from: fifthMonth) // Error: value not unwrapped
let fifthMonth = Month(rawValue: 5)!
monthsUntilWinterBreak(from: fifthMonth) // 7
String raw values
enum Icon: String {
case music
case sports
case weather
var filename: String {
// 2
return "\(rawValue.capitalized).png"
}
}
let icon = Icon.weather
icon.filename // Weather.png
Associated values
- 每個(gè)枚舉值都有0個(gè)或者多個(gè)關(guān)聯(lián)值
- 每個(gè)枚舉值的關(guān)聯(lián)值都有自己的數(shù)據(jù)類型
- 你可以像定義方法參數(shù)一樣定義關(guān)聯(lián)值
enum WithdrawalResult {
case success(newBalance: Int)
case error(message: String)
}
let result = WithdrawalResult.success(newBalance: 100)
//let result = WithdrawalResult.error(message: "測試錯(cuò)誤數(shù)據(jù)")
switch result {
case .success(let newBalance):
print("Your new balance is: \(newBalance)")
case .error(let message):
print(message)
}
switch result {
case .success(let newBalance):
print("Your new balance is: \(newBalance)")
case .error(let message):
print(message)
}
//多個(gè)關(guān)聯(lián)值
enum WithdrawalResult {
case success(newBalance: Int,parameters: Int)
case error(message: String)
}
特殊的條件判斷
enum HTTPMethod {
case get
case post(body: String)
}
let request = HTTPMethod.post(body: "Hi there")
/*
In this code, guard case checks to see
if request contains the post enumeration case and if so,
reads and binds the associated value.
guard case 判斷 request 是否是post 斋日,如果是post,讀取并且關(guān)聯(lián)值到body
*/
guard case .post(let body) = request else {
fatalError("No message was posted")
}
print(body)
//與上面語句判斷等同
if case .post(let body) = request {
print(body)
}
Optionals
Optionals 的底層實(shí)現(xiàn)就是枚舉墓陈,只是編譯器隱藏了實(shí)現(xiàn)細(xì)節(jié)恶守,包括可選值綁定 ? 和 贡必! 操作符孙乖,以及nil的實(shí)現(xiàn)栈源。
var age: Int?
age = 17
age = nil
switch age {
case .none:
print("No value")
case .some(let value):
print("Got a value: \(value)")
}
if let age = age {
print("\(age)")//17
}
if (age != nil) {
print("\(age)")//Optional(17)
}
error
//Optional type 'Int?' cannot be used as a boolean; test for '!= nil' instead
if age {
print("\(age)")
}
Key points
An enumeration is a list of related values that define a common type. 枚舉是定義公共類型的相關(guān)值的列表爹凹。
Enumerations provide an alternative to old-fashioned integer values.枚舉提供了一種替代老式整數(shù)值的方法
You can use enumerations to handle responses, store state and encapsulate values.您可以使用枚舉來處理響應(yīng)了罪,存儲(chǔ)狀態(tài)和封裝值。
Case-less enumerations prevent the creation of instances.枚舉里枚舉值為空不允許創(chuàng)建實(shí)例理逊。