课程来自慕课网liuyubobobo老师
枚举
- 枚举基础
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 Season {
case Spring, Summer, Autumn, Winter
}
let month1 = Month.November
let month2: Month = .November
func season (month: Month) -> Season {
switch month {
case .March, .April, .May:
return .Spring
case .June, .July, .August:
return .Summer
case .September, .October, .November:
return .Autumn
case .December, .January, .February:
return .Winter
}
}
season(month: .November)
- 枚举之原始值
enum ProgrammingLanguage: String {
case Swift = "Swift"
case OC = "Objective-C"
case C
case Java
}
let pm1: ProgrammingLanguage = .OC
print(pm1.rawValue) // "Objective-C"
let pm2: ProgrammingLanguage = .C
print(pm2.rawValue) // "C"
- 枚举之关联值
enum ATMStatus {
case Success(Int)
case Error(String)
case Waiting
}
// 余额 1000 元
var balance = 1000
// 取钱操作
func withdraw(amount: Int) -> ATMStatus {
if balance >= amount {
balance -= amount
return .Success(balance)
}else {
return .Error("Not enought money")
}
}
switch withdraw(amount: 800) {
case let .Success(newBalance):
print("\(newBalance) Yuan left")
case let .Error(errorMessage):
print("Error:\(errorMessage)")
case .Waiting:
print("Waiting")
}
- 枚举递归
indirect enum ArithmeticExpression{
case Numebr(Int)
case Addition( ArithmeticExpression, ArithmeticExpression)
case Multiplication( ArithmeticExpression, ArithmeticExpression)
}
网友评论