本篇作为Swift的第四篇,主要介绍了Swift中的枚举类型,它和其它语言相比有其特殊性
An enumeration can have methods, computed properties and protocol declarations, all while acting as a nice state machine.
enum 声明一个枚举
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
}
. 存取枚举中的内容,利用Swift的类型推导可以省去枚举名
func schoolSemester(month: Month) -> String {
switch month {
case .August, .September, .October, .November, .December:
return "Autumn"
case .January, .February, .March, .April, .May:
return "Spring"
default:
return "Not in the school year"
}
}
String, Float或 Character,更为灵活,被赋予的raw value也可以是无序的
//如果省略了第一个之后的默认原始值,则编译器会自增赋值
enum Month: Int {
case January = 1, February = 2, March = 3, April = 4, May = 5, June = 6, July = 7, August = 8, September = 9, October = 10, November = 11, December = 12
}
rawValue 属性来存取原始值(raw value)
func monthsUntilWinterBreak(month: Month) -> Int {
return Month.December.rawValue - month.rawValue
}
monthsUntilWinterBreak(.April) // 8
//Enumeration initializers with the rawValue: parameter are failable initializers, meaning if things go wrong, the initializer will return nil.
//这里初始化函数不能保证你赋予的原始值在枚举类型中存在,因此返回一个Optional
let fifthMonth = Month(rawValue: 5)
monthsUntilWinterBreak(fifthMonth) // Error: value not unwrapped
//安全的做法
if let fifthMonth = Month(rawValue: 5) {
monthsUntilWinterBreak(fifthMonth) // 7
}
//银行取款的例子,有余额则做计算,余额不足则显示错误信息,这两种操作的结果是不同类型的
var balance = 100
enum WithdrawalResult {
case Success(Int)
case Error(String)
}
func withdraw(amount: Int) -> WithdrawalResult {
if amount <= balance {
balance -= amount
return .Success(balance)
} else {
return .Error("Not enough money!")
}
}
let result = withdraw(99)
switch result {
case let .Success(newBalance):
print("Your new balance is: \(newBalance)")
case let .Error(message):
print(message)
}
//存取枚举的关联值在现实生活中的例子很多
//服务器通常用枚举区分不同类型的请求
enum HTTPMethod {
case GET
case POST(String)
}
enum TrafficLight {
case Red, Yellow, Green
}
let trafficLight = TrafficLight.Red
? 声明一个Optional
let email: Optional<String> = .None
let website: Optional<String> = .Some("devqiao.net") //associated value
switch website {
case .None:
print("No value")
case let .Some(value):
print("Got a value: \(value)")
}
Swift hides the implementation details with things like if-let binding, the ? and ! operators, and keywords such as nil.
// nil和.None在底层是相同的值 let optionalNil: Optional<Int> = .None optionalNil == nil // true optionalNil == .None // true