在Swift中,枚举可以有关联值、原始值和方法,这些高级使用方法可以使枚举更加灵活和功能强大。
enum Result {
case success(Int)
case failure(String)
}
let result1 = Result.success(10)
let result2 = Result.failure("Error")
enum Weekday: Int {
case monday = 1
case tuesday = 2
case wednesday = 3
}
let day = Weekday.monday.rawValue
enum TrafficLight {
case red
case yellow
case green
func message() -> String {
switch self {
case .red:
return "Stop"
case .yellow:
return "Caution"
case .green:
return "Go"
}
}
}
let light = TrafficLight.red
let message = light.message() // "Stop"
这些高级使用方法使枚举更加灵活和功能强大,可以更好地适应各种需求。