当前位置: 首页 > 编程学习 > 其它语言 > Swift > 正文

Swift4 枚举,例子代码

2018-04-22 来源:博客园/CC_Joy

枚举

苹果官方文档 枚举

苹果官方文档中文翻译 枚举

枚举语法

enum SomeEnumeration {
    // enumeration definition goes here
}
enum CompassPoint {
    case north
    case south
    case east
    case west
}
 
var directionToHead = CompassPoint.west
 
directionToHead = .east
enum Planet {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}

使用Switch语句来匹配枚举值

directionToHead = .south
switch directionToHead {
    case .north:
        print("Lots of planets have a north")
    case .south:
        print("Watch out for penguins")
    case .east:
        print("Where the sun rises")
    case .west:
        print("Where the skies are blue")
}
// prints "Watch out for penguins"

如果不能为所有枚举成员都提供一个 case,那你也可以提供一个 default 情况来包含那些不能被明确写出的成员:

let somePlanet = Planet.earth
switch somePlanet {
    case.earth:
        print("Mostly harmless")
    default:
        print("Not a safe place for humans")
}
// Prints "Mostly harmless"

关联值

enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
 
switch productBarcode {
    case .upc(let numberSystem, let manufacturer, let product, let check):
        print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
    case .qrCode(let productCode):
        print("QR code: \(productCode).")
}
// Prints "QR code: ABCDEFGHIJKLMNOP."

如果对于一个枚举成员的所有的相关值都被提取为常量,或如果都被提取为变量,为了简洁,你可以用一个单独的 var或 let在成员名称前标注:

switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
    print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
    print("QR code: \(productCode).")
}
// Prints "QR code: ABCDEFGHIJKLMNOP."

原始值

枚举成员可以用相同类型的默认值预先填充(称为原始值)。

enum ASCIIControlCharacter: Character {
    case tab = "\t"
    case lineFeed = "\n"
    case carriageReturn = "\r"
}

隐式指定的原始值

当你在操作存储整数或字符串原始值枚举的时候,你不必显式地给每一个成员都分配一个原始值。当你没有分配时,Swift 将会自动为你分配值。

enum Planet: Int {
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
 
enum CompassPoint: String {
    case north, south, east, west
}
 
let earthsOrder = Planet.Earth.rawValue
    // earthsOrder is 3
 
let sunsetDirection = CompassPoint.west.rawValue
    // sunsetDirection is "west"

从原始值初始化

用原始值类型来定义一个枚举,那么枚举就会自动收到一个可以接受原始值类型的值的初始化器(叫做rawValue的形式参数)然后返回一个枚举成员或者 nil

let possiblePlanet = Planet(rawValue: 7)
    // possiblePlanet is of type Planet? and equals Planet.Uranus

原始值初始化器是一个可失败初始化器

let positionToFind = 11
if let somePlanet = Planet(rawValue: positionToFind) {
    switch somePlanet {
    case .earth:
        print("Mostly harmless")
    default:
        print("Not a safe place for humans")
    }
} else {
    print("There isn't a planet at position \(positionToFind)")
}
// Prints "There isn't a planet at position 11"

递归枚举

递归枚举是拥有另一个枚举作为枚举成员关联值的枚举。在声明枚举成员之前使用indirect关键字来明确它是递归的。

enum ArithmeticExpression {
    case number(Int)
    indirect case addition(ArithmeticExpression, ArithmeticExpression)
    indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}

可以在枚举之前写==indirect==来让整个枚举成员在需要时可以递归:

indirect enum ArithmeticExpression {
    case number(Int)
    case addition(ArithmeticExpression, ArithmeticExpression)
    case multiplication(ArithmeticExpression, ArithmeticExpression)
}
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
func evaluate(_ expression: ArithmeticExpression) -> Int {
    switch expression {
    case let .number(value):
        return value
    case let .addition(left, right):
        return evaluate(left) + evaluate(right)
    case let .multiplication(left, right):
        return evaluate(left) * evaluate(right)
    }
}
 
print(evaluate(product))
// Prints "18"