在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"
這些高級使用方法使枚舉更加靈活和功能強大,可以更好地適應各種需求。