Swift Enum(枚举)

  • 出自:huazhume

前言

枚举 相信大家都不会陌生,因为在不管是Java,OC,C++等语言中都存在这个类型,而在使用过程中也是多变的。当然它帮助我们解决了众多 指定 和 赋值 便易 问题

定义一个枚举
enum Month : Int {
    case January
    case February
    case March
    case April
    case May
    case June
    case july
    case Auguest
    case Septemper
    case October
    case November
    case December
}
简写也是可以的
enum Season{
    case Spring,Summer,Autumn,Winter
}'
使用枚举
let curMonth : Month = Month.March
let curMonth2 : Month = .March
枚举也是可以定义方法的
func sumDays() -> Int {
    switch self {
    case .January:
        return 40
    default:
        return 30
    }
}

func monthsBeforeNewYear(month: Month2)->Int{
    return 12 - month.rawValue
}

我们可以根据枚举的“Raw value (值)“来匹配相对应的”枚举项“,但有时候有匹配不到的,那这个时候就会返回nil

let input = 100; //100在枚举中是不存在的
let month = Month2(rawValue: input)
//解包
if let month = Month2(rawValue: input){
    print(month)
}
枚举Associate value(关联值)

Swift给枚举引入了"关联值",这个就方便我们去阐述这个枚举代表的含义或者体现它的“

enum ATMStatus {
    case Success(Int) //关联一个Int值
    case Error(String) //关联一个String值
}

var balance = 1000
func withdraw (amount : Int) -> ATMStatus {
    if balance >= amount  {
        balance -= amount
        return .Success(balance)
    }
    return .Error("Not enough money")
}

let result = withdraw(amount: 100)
switch result{
    case let .Success(newBalance):
        print(newBalance)
    case let .Error(errorMessage):
        print(errorMessage)
}

注意 Raw value 和 Associate value 不可共存

回归可选型

还记得可选型吗?,它可以存一个值为 nil,是不是我们可以定一个枚举,然后里面包含一个nil的值,不就实现了一个可选型吗!!

的确可选型就是这样实现:

var website : Optional = Optional.some("imooc.com")
website = .none

相当于

var website2 : String? = "imooc.com"
website2 = nil

可选型的取值

switch website{
    case .none:
        print("nil")
    case let .some(website):
        print(website)
}
枚举实现递归定义:
//递归定义的变量
indirect enum ArithmeticExpression{
    case Number(Int)
    case Addition(ArithmeticExpression,ArithmeticExpression)
    case Multiplication(ArithmeticExpression,ArithmeticExpression)
}
//(5 + 4) * 2

let five:ArithmeticExpression = .Number(5)
let four:ArithmeticExpression = .Number(4)
let sum:ArithmeticExpression = .Addition(five, four)
let two:ArithmeticExpression = .Number(2)
let mult:ArithmeticExpression = .Multiplication(two, sum)

func evaliate(expression: ArithmeticExpression)-> Int{
    switch expression {
        case let .Number(number4):
            return number4
        case let .Addition(left, right):
            return evaliate(expression: left) + evaliate(expression: right)
        case let .Multiplication(left ,right):
            return evaliate(expression: left) + evaliate(expression: right)
    }
}
evaliate(expression: mult)

你可能感兴趣的:(Swift Enum(枚举))