1. 枚举的定义:
// 定义一个简单的枚举
enum CompassDirection {
case north
case south
case east
case west
}
2. 使用枚举值:
// 使用枚举值
var direction: CompassDirection = .north
direction = .east
3. 与 Switch 语句结合使用:
switch direction {
case .north:
print("向北")
case .south:
print("向南")
case .east:
print("向东")
case .west:
print("向西")
}
4. 关联值:
枚举可以带有关联值,允许在不同的枚举成员中存储不同类型的值。
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
var productCode: Barcode = .upc(8, 85909, 51226, 3)
switch productCode {
case .upc(let numberSystem, let manufacturer, let product, let check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check)")
case .qrCode(let code):
print("QR Code: \(code)")
}
5. 原始值:
枚举可以关联原始值,这些原始值可以是字符串、整数等类型。
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
let earthOrder = Planet.earth.rawValue
6. 通过原始值初始化枚举实例:
if let somePlanet = Planet(rawValue: 3) {
print("第三颗行星是 \(somePlanet)")
} else {
print("无效的行星编号")
}
这里,rawValue 是可用于获取枚举成员的原始值的属性。
7. 递归枚举:
枚举可以是递归的,允许一个枚举成员包含相同类型的枚举实例。
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
let expression = ArithmeticExpression.addition(
.number(2),
.multiplication(
.number(3),
.number(4)
)
)
这个例子中,addition 和 multiplication 的关联值都是 ArithmeticExpression 类型的枚举实例。
这些是一些基本的枚举操作。Swift 的枚举提供了很多灵活性,可用于定义一组相关值,并使代码更加清晰和可读。
转载请注明出处:http://www.pingtaimeng.com/article/detail/6848/Swift