Swift 学习笔记 enum 枚举类型

时间:2024-06-11 11:05:26

异端,异端啊,我感觉这是map吧?

 enum ATMStatus {
     case Success(Int)
     case Error(String)
 }

 func withdraw(amount: Int) -> ATMStatus {
     if balance >= amount {
         balance -= amount
         return .Success(balance)
     } else {
         return .Error("QiongB")
     }
 }

 let result = withdraw()

 switch result {
 case .Success:
     //print(money)
     print("I am here")
     break
 case let .Error(msg):
     print(msg)
     break
 }

还可以递归包含,但是声明的enum前面要加indirect

 indirect enum Expression {
     case Number(Int)
     case Addition(Expression, Expression)
     case Multiply(Expression, Expression)
 }

 //(5 + 4) * 2
 let five = Expression.Number()
 let four = Expression.Number()
 let sum = Expression.Addition(five, four)
 let multi = Expression.Multiply(sum, four)

 func compute(expression: Expression) -> Int {
     switch expression {
     case let .Number(value):
         return value
     case let .Addition(left, right):
         return compute(left) + compute(right)
     case let .Multiply(left, right):
         return compute(left) * compute(right)
     }
 }

 compute(multi)

学习进度缓慢,咸鱼