Swift学习笔记四之枚举

枚举:

enum CompassPoint{
        case north
        case south
        case east
        case west
}
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")
        }

当不需要匹配每个枚举成员的时候,你可以提供一个default分支来涵盖所有未明确处理的枚举成员

enum Planet: Int {
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}

enum CompassPoint: String {
    case north, south, east, west
}

递归枚举:
它有一个或多个枚举成员使用该枚举类型的实例作为关联值。使用递归枚举时,编译器会插入一个间接层,你可以在枚举成员前加上indirect 来表示该成员可递归

enum Arth {
    case Number(Int)
    indirect case Add(Arth,Arth)
    indirect case Mul(Arth,Arth)
}

 let five = Arth.Number(5)
        let four = Arth.Number(4)
        let sum = Arth.Add(five, four)
        let result = Arth.Mul(sum, Arth.Number(2))
        print(result)
        
        
        print(evaluate(express: result))

func evaluate(express:Arth) -> Int {
        switch express {
        case .Number(let value):
            return value
        case .Add(let left, let right):
            return evaluate(express: left) + evaluate(express: right)
        case .Mul(let left, let right):
            return evaluate(express: left) * evaluate(express: right)
        }
    }

你可能感兴趣的:(Swift学习笔记四之枚举)