8、【Swift】枚举 - Enumerations

2020-12-14  本文已影响0人  Sunday_David

枚举语法

enum SomeEnumeration {
    // 枚举定义放在这里
}
enum CompassPoint {
    case north
    case south
    case east
    case west
}

与 C 和 Objective-C 不同,northsoutheastwest 不会被隐式地赋值为 0123

每个成员都被定义为的 CompassPoint 类型

enum Planet {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
var directionToHead = CompassPoint.west
directionToHead = .east

使用 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")
}
// 打印“Watch out for penguins”
let somePlanet = Planet.earth
switch somePlanet {
case .earth:
    print("Mostly harmless")
default:
    print("Not a safe place for humans")
}
// 打印“Mostly harmless”

枚举成员的遍历

for beverage in Beverage.allCases {
    print(beverage)
}
// coffee
// tea
// juice

关联值 - (外部赋值)

关联值 跟其他语言中的可识别联合(discriminated unions),标签联合(tagged unions),或者变体(variants)相似

img img
enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
// 关联的元组值为 (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).")
}
// 打印“QR code: ABCDEFGHIJKLMNOP.”
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
    print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
    print("QR code: \(productCode).")
}
// 打印“QR code: ABCDEFGHIJKLMNOP.”

原始值 - Raw Values - (内部赋值)

// 原始值被定义为类型 Character
enum ASCIIControlCharacter: Character {
    case tab = "\t"
    case lineFeed = "\n"
    case carriageReturn = "\r"
}

与关联值的区别:

原始值内部赋值一次,不会改变。关联值,外部随时赋值,随时改变

原始值的隐式赋值 - 自动默认值

// 整型原始值, 如果不手动设置,第一个默认为0, 后面一次递增1
enum Planet: Int, CaseIterable {
    case mercury = 1,  venus, earth, mars, jupiter, saturn, uranus, neptune
}
for planetNum in Planet.allCases {
    print("planetNum = \(planetNum.rawValue)")
    print("--------------------")
}
enum CompassPoint: String, CaseIterable {
    case north, south, east, west
}

for point in CompassPoint.allCases {
    print("point = \(point.rawValue)")
    print("--------------------")
}

使用原始值初始化枚举实例 - 外部赋值

let possiblePlanet = Planet(rawValue: 7)
// possiblePlanet 类型为 Planet? 值为 Planet.uranus

原始值构造器是一个可失败构造器,因为并不是每一个原始值都有与之对应的枚举成员。更多信息请参见 可失败构造器

let positionToFind = 11
if let somePlanet = Planet(rawValue: positionToFind) { // 可选绑定(optional binding)
    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)")
}
// 打印“There isn't a planet at position 11”

递归枚举

enum ArithmeticExpression {
    case number(Int)
    indirect case addition(ArithmeticExpression, ArithmeticExpression)
    indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
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))
// 打印“18”
上一篇下一篇

猜你喜欢

热点阅读