创建枚举
enum Direction {
case east
case south
case west
case north
}
成员值前加“case”关键字。
也可以使用一个case声明所有成员值
enum Direction {
case east, south, west, north
}
使用
var direction = Direction.south
direction = .east
如果确定变量的是某个枚举类型,那么我们使用时可以省略枚举类型,直接使用“.成员值”,这点比Java做得好。
关联值
Swift的枚举还能这么使用
enum Barcode {
// 条形码类型
case upc(Int, Int, Int, Int)
// 二维码类型
case qrCode(String)
}
这样创建的话,我们定义和使用时,不止可以使用枚举类型,还能设置和获取类型的关联值。
我们可以这么使用
var code = Barcode.upc(110, 111, 112, 113)
code = .qrCode("ABCDEFG")
好像只能在switch取值
switch code {
case .upc(let a, let b, let c, let d) :
print("\(a) \(b) \(c) \(d)")
break
case .qrcode(let a) :
print("\(a)")
break
}
由于upc的参数比较多,还有一种简便的写法,把 let 紧跟在 case 后面
switch code {
case let .upc(a, b, c, d) :
print("\(a) \(b) \(c) \(d)")
break
case let .qrcode(a) :
print("\(a)")
break
}
原始值
在Swift中,也是可以定义成员的原始值
enum Direction: String {
case east = "East"
case west = "Weat"
case south = "South"
case north = "North"
}
获取成员的原始值
var direction = Direction.east.rawValue
我们在定义原始值时,如果是Int类型的,只需要定义第一个值,Swift会帮我们推断出其他的值
enum Number: Int {
case one = 1
case two
case three
case four
case five
case six
case seven
}
Number.five.rawValue // 值为5
有意思吧!!