Swift学习笔记-枚举

2018-05-23  本文已影响0人  女粉丝

1.多个成员值可以在同一行上,用,分开

enum direction {
        case east,west
        case north
        case sourth
    }

2.当变量的类型已知为枚举型时,可以用 .east赋值。(如tab.separatorStyle = .singleLine)

3.关联值。

enum direction {
        case east,west(Int,Int)
        case north(String)
    }

//如果后面要改变内部枚举类型的值,这里必须为var。只能拥有一个关联值,相当于枚举时的枚举值切换。
var x = direction.west(1, 2)
        x = .north("zc")
        
        switch x {
        case let .west(a, b):
            print(a+b)
        case let .north(c):
            print(c)
        default:
            print("default")
        }

4.设置原始值,需要在枚举后面加上类型,字符串默认就是枚举的名字,Int默认为0 依次+1.(枚举值的类型必须为字符,整型,浮点型,不可为元祖)
取值时使用rawValue

enum direction:Int {
        case east = 1
        case north = 2
        case sourth = 3
    }

let x = direction.west.rawValue
if  let x = direction(rawValue: 2){
            switch x {
            case .east:
                print("一路向东")
            default:
                print("不走了")
            }
        }else{
            print("没有改值")
        }

5.递归枚举,就是在枚举中仍然使用该枚举类型。

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

func evalute (_ expression: ArithmeticExpression) -> Int {
        
        switch expression {
        case let .number(a):
            return a
        case let .addition(a, b):
            return evalute(_:a)+evalute(_:b)
        case let .multiplication(a, b):
            return evalute(_:a)*evalute(_:b)
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读