枚举
- 写法(以
enum
关键字开头,后跟名称,{}
内是枚举内容,每一个枚举值使用关键字case
标志)
enum Week {
case Monday
case Tuesday
case Wednesday
case Thursday
case Friday
case Saturday
case Sunday
}
enum anotherWeek {
case Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
}
//简单写法
enum Week {
case Monday
case Tuesday
case Wednesday
case Thursday
case Friday
case Saturday
case Sunday
}
//合并写法
enum anotherWeek {
case Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
}
//定义枚举变量
var first = Week.Monday
var second = anotherWeek.Saturday
//枚举值匹配,匹配时,我们必须明确枚举内的每个值都不会遗漏
switch first {
case .Monday,.Tuesday,.Wednesday,.Thursday,.Friday:
print("工作日")
case .Saturday,.Sunday:
print("休息")
}
//当不需要详尽匹配时,我们也可以使用"default"来标识不需要明确处理的成员
switch second {
case .Monday,.Tuesday,.Wednesday,.Thursday,.Friday:
print("工作日")
default:
print("休息")
}
- 值关联(我们可以在枚举中提供相关类型的关联值,在使用switch进行匹配时,我们可以用
let
或者var
来提取每个变量,当整个分支语句的所有变量都需要提取时,我们可以把let
或者var
写在成员变量前)
enum Request {
case result(Int,String)
}
var success = Request.result(200, "Success")
switch success {
case .result(let code,let message):
print("the resultCode is \(code) request \(message)")
}
switch success {
case let .result(code,message):
print("the resultCode is \(code) request \(message)")
}
- 原始值:
在Swift中,定义枚举时,如果我们给枚举设置类型,那么枚举的每个成员都会相应的附上一个对应类型的原始值,此时我们可以根据这个原始值来生成枚举中的一个变量.
以下面代码为例,Week(rawValue:str)
会返回一个Week?
的类型,所以我们对他进行枚举时,必须确保其不为nil
enum Week:String {
case Monday
case Tuesday
case Wednesday
case Thursday
case Friday
case Saturday
case Sunday
}
var str = "Monday"
if var strOfWeek = Week(rawValue: str) {
switch strOfWeek {
case .Monday,.Tuesday,.Wednesday,.Thursday,.Friday:
print("工作日")
default:
print("休息")
}
}
- 递归枚举(在成员变量前,加
indirect
关键字,表明该成员可以被递归)
enum ArithmeticExpression {
case number(Int)
indirect case addition(ArithmeticExpression, ArithmeticExpression)
indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
let value1 = ArithmeticExpression.number(4)
let value2 = ArithmeticExpression.number(5)
let sum = ArithmeticExpression.addition(value1, value2)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
func evalute(_ expression:ArithmeticExpression) ->Int {
switch expression {
case let .number(a):
return a
case let .addition(value1, value2):
return evalute(value1) + evalute(value2)
case let .multiplication(value1,value2):
return evalute(value1) * evalute(value2)
}
}
evalute(product)
网友评论