Swift4学习

Swift4-枚举

2018-08-09  本文已影响279人  wingsrao

枚举

1.枚举为一组相关值定义了一个通用类型,从而可以让你在代码中类型安全地操作这些值。

2.Swift 的枚举成员在被创建时不会分配一个默认的整数值。

3.每个枚举都定义了一个全新的类型,需要首字母大写。

var directionToHead = CompassPoint.west
directionToHead = .east //赋值后,类型被自动推断出来
  1. swift4.2新特性:在枚举名字后面写 : CaseIterable 来允许枚举被遍历,所有情况的集合名为 allCases。
enum Beverage: CaseIterable {
    case coffee, tea, juice
}
let numberOfChoices = Beverage.allCases.count
print("\(numberOfChoices) beverages available")

5.多个成员值可以出现在同一行中,要用逗号隔开:

enum Planet {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}

6.关联值:

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 let .upc(numberSystem, manufacturer, product, check):
    print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
    print("QR code: \(productCode).")
}
// Prints "QR code: ABCDEFGHIJKLMNOP."
//在给定的时间内只能存储其中一个值

7.原始值:特定枚举成员的原始值是始终相同的。关联值在你基于枚举成员的其中之一创建新的常量或变量时设定,并且在你每次这么做的时候这些关联值可以是不同的。

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

8.递归枚举:
你可以在声明枚举成员之前使用 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)
}

递归函数是一种操作递归结构数据的简单方法。比如说,这里有一个判断数学表达式的函数:

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"
上一篇下一篇

猜你喜欢

热点阅读