• Swift-----枚举enum


    1 定义枚举时,如果不写后面等于的值,默认是从0开始的,依次加1.

    enum Month: Int {
        case January = 1
        case February = 2
        case March = 3
        case April = 4
        case May = 5
        case June = 6
        case July = 7
        case August = 8
        case September = 9
        case October = 10
        case November = 11
        case December = 12
    }
    
    enum Season {
        case Spring, Summer, Autumn, Winter
    }
    
    func season(month: Month) -> Season {
        switch (month) {
        case .March, .April, .May:
            return .Spring
        case .June, .July, .August:
            return .Summer
        case .September, .October, .November:
            return .Autumn
        case .December, .January, .February:
            return .Winter
        }
    }
    
    func monthBeforeNewYear(month: Month) -> Int {
        return 12 - month.rawValue
    }
    
    let month = Month.April
    monthBeforeNewYear(month: month)
    
    let month1 = Month(rawValue: 4)
    if let month1 = month1 {
        monthBeforeNewYear(month: month1)
    }

    2 枚举的类型,默认是Int类型,也可以是其他类型,例如字符串。

      如果不写值,默认就是定义case时的字符串

    enum pargramingLanguage: String {
        case Swift
        case ObjecticeC = "Objective-C"
        case JavaScript = "javaScript"
        case PHP
    }
    
    let language = pargramingLanguage.Swift
    print("(language.rawValue) is my favorite language.")  // Swift is my favorite language.

    3 Raw Value

    enum Money: Int {
        case Yuan = 100
        case Jiao = 10
        case Fen = 1
    }

    3 Associate Value(关联值)

    enum ATMState {
        case Success(Int)
        case Error(String)
        case Waiting
    }
    
    var balance = 1000
    
    func withdraw(amount: Int) -> ATMState {
        if balance >= amount {
            return .Success(balance - amount)
        } else {
            return .Error("Not enough money.")
        }
    }
    
    let result = withdraw(amount: 400)
    switch result {
    case let .Success(newBalance):
        print("(newBalance) yuan left in your amount.")
    case let .Error(errorMessage):
        print("error: (errorMessage)")
    case .Waiting:
        print("Waiting")
    }
    
    // 也可以不用解析关联值
    switch result {
    case .Success:
        print("Success")
    case .Error:
        print("Error")
    case .Waiting:
        print("Waiting")
    }

    4 也可以关联多个值

    enum Shape {
        case Square(side: Double)
        case Rectangle( Double, height: Double)
        case Circle(centerx: Double, centery: Double, radius: Double)
        case Point
        
        func area() -> Double {
            switch self {
            case let .Square(side):
                return side * side
            case let .Rectangle(width, height):
                return width * height
            case let .Circle(_, _, radius):
                return radius * radius
            case .Point:
                return 0
            }
        }
    }
    
    let square = Shape.Square(side: 20)
    let rectangle = Shape.Rectangle( 10, height: 20)
    let circle = Shape.Circle(centerx: 0, centery: 0, radius: 10)
    let point = Shape.Point
    
    square.area()
    rectangle.area()
    circle.area()
    point.area()

    5 可选型(Optional)实际上就是枚举

    var string: Optional<String> = Optional.some("A string")  // Optional<String>实际上就是String?
    
    switch (string) {
    case .none:
        print("String is nil.")
    case let .some(value):
        print("String is (value).")
    }
    
    // 解包简化为:
    if let string = string {
        print("String is (string).")
    }
    
    string = .none        // nil

     6 枚举递归(在enum前面加indirect关键字,或者是在需要递归的case语句的case前面加关键字)

    indirect enum ArithmeticExpression {
        case Number(Int)
        case Addition(ArithmeticExpression, ArithmeticExpression)
        case Multiplication(ArithmeticExpression, ArithmeticExpression)
    }
    // 或者可以这样定义枚举
    enum ArithmeticExpression {
      case Number(Int)
      indirect case Addition(ArithmeticExpression, ArithmeticExpression)
      indirect case Multiplication(ArithmeticExpression, ArithmeticExpression)
    }
    // 计算这个表达式 (5 + 4) * 2 let five = ArithmeticExpression.Number(5) let four = ArithmeticExpression.Number(4) let add = ArithmeticExpression.Addition(five, four) let two = ArithmeticExpression.Number(2) let result = ArithmeticExpression.Multiplication(add, two) func evaluate(expression: ArithmeticExpression) -> Int { switch expression { case let .Number(number): return number case let .Addition(num1, num2): return evaluate(expression: num1) + evaluate(expression: num2) case let .Multiplication(num1, num2): return evaluate(expression: num1) * evaluate(expression: num2) } } evaluate(expression: result)  // 18    

    7 枚举中也可以定义方法

    enum Shape {
        case Square(side: Double)
        case Rectangle( Double, height: Double)
        case Circle(centerx: Double, centery: Double, radius: Double)
        case Point
        
        func area() -> Double {
            switch (self) {
            case let .Square(side):
                return side * side
            case let .Rectangle(width, height):
                return width * height
            case let .Circle(_, _, radius):
                return M_PI * radius * radius
            case .Point:
                return 0
            }
        }
    }
    
    let square = Shape.Square(side: 20)
    let rectangle = Shape.Rectangle( 10, height: 20)
    let circle = Shape.Circle(centerx: 0, centery: 0, radius: 10)
    let point = Shape.Point
    
    square.area()
    rectangle.area()
    circle.area()
    point.area()
    8 枚举也是值类型
    let circle = Shape.Circle(centerx: 0, centery: 0, radius: 10)
    var point = circle
    point = Shape.Point
    
    point   // Point
    circle  // Circle(0.0, 0.0, 10.0)
    9 如果要在一个枚举中定义一个方法来改变自身的状态,需要在方法前添加关键字mutating
    enum Swich {
        case on
        case off
        
        mutating func changeState() {
            switch(self) {
            case .off:
                self = .on
            case .on:
                self = .off
            }
        }
    }
  • 相关阅读:
    【项目】项目27
    【项目】项目26
    【项目】项目25
    【项目】项目24
    【项目】项目23
    【项目】项目22
    【项目】项目21
    【项目】项目20
    【项目】项目19
    【项目】项目18【项目】项目18
  • 原文地址:https://www.cnblogs.com/muzijie/p/6543934.html
Copyright © 2020-2023  润新知