//: Playground - noun: a place where people can play import UIKit //Raw Value enum Month: String{ case January = "Value_January" case February = "Value_February" case March = "Value_March" case April = "Value_April" case May = "Value_May" case June = "Value_June" case July = "Value_July" case August = "Value_August" case September = "Value_September" case October = "Value_October" case November = "Value_November" case December = "Value_December" } func season(month: Month ) -> String{ switch month { case .January: return month.rawValue default: return "" } } season(month: Month.January) print(Month.April) if let july = Month(rawValue: "Value_July"){ print(july) } //Associate Value //例1 enum ATMStatus{ case Success(Int) case Error(String) case Waiting } var balance = 1000 func withdraw( amount: Int ) -> ATMStatus{ if amount <= balance { balance -= amount return .Success(balance) } else { return .Error("Not enough money") } } let result = withdraw(amount: 800) switch result { case let .Success(newBalance): print("\(newBalance) Yuan Left in your account.") 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") } //例2 enum Shape{ case Square(side: Double) case Rectangle(width: Double, height: Double) case Circle(centerX: Double, centerY: Double, radius: Double) case Point } let square = Shape.Square(side: 10) let rectangle = Shape.Rectangle(width: 20, height: 30) let circle = Shape.Circle(centerX: 0, centerY: 0, radius: 15) let point = Shape.Point func area(shape: Shape) -> Double{ switch shape { case let .Square(side): return side * side case let .Rectangle(width, height): return width * height case let .Circle(_, _, r): return M_PI * r * r case .Point: return 0 } } area(shape: square) area(shape: rectangle) area(shape: circle) area(shape: point)
时间: 2024-11-10 16:15:46