枚举为一组相关值定义了一个通用类型,从而可以让你在代码中类型安全地操作这些值。
基本用法
enum RequestType{
case get
case post
case put
case delete
}
原始值(Raw Values)
// 原始值, 不写默认是枚举值
enum Grade: String {
case perfect = "A"
case great = "B"
case good = "C"
case bad = "D"
}
print(Grade.perfect) // perfect
print(Grade.perfect.rawValue) // A
如果枚举的原始值类型是Int、String
,Swift会自动分配原始值
enum Season : Int {
case spring, summer, autumn, winter
}
print(Season.spring.rawValue) // 0
print(Season.summer.rawValue) // 1
print(Season.autumn.rawValue) // 2
print(Season.winter.rawValue) // 3
关联值
将枚举的成员值 跟其他类型的关联存储在一起,有时会非常有用。
enum Date {
case digit(year: Int, month: Int, day: Int)
case string(String)
}
var date = Date.digit(year: 2011, month: 9, day: 10)
date = .string("2011-09-10")
switch date {
case .digit(let year, let month, let day):
print(year, month, day)
case let .string(value): // ? ? ?
print(value)
}
递归枚举
枚举值包含自己枚举,需要使用indirect
关键字
indirect enum ArithExpr {
case number(Int)
case sum(ArithExpr, ArithExpr)
case difference(ArithExpr, ArithExpr)
}
let five = ArithExpr.number(5)
let four = ArithExpr.number(4)
let two = ArithExpr.number(2)
let sum = ArithExpr.sum(five, four)
let difference = ArithExpr.difference(sum, two)
可以使用MemoryLayout
获取数据类型占用的内存大小
enum Password {
case number(Int, Int, Int, Int)
case other
}
MemoryLayout<Password>.stride // 40, 分配占用的空间大小
MemoryLayout<Password>.size // 33, 实际用到的空间大小
MemoryLayout<Password>.alignment // 8, 对齐参数
网友评论