Introduction
Enums in Swift help group related values together in a clear way. They make your code safer and easier to understand.
Enums in Swift help group related values together in a clear way. They make your code safer and easier to understand.
enum EnumName { case option1 case option2 case option3 }
Each case represents a possible value of the enum.
You can add extra data to cases using associated values.
enum Direction { case north case south case east case west }
enum Barcode { case upc(Int, Int, Int, Int) case qrCode(String) }
enum Result { case success(String) case failure(Error) }
This program uses an enum to represent traffic light colors. It returns an action for each color using a switch statement.
enum TrafficLight { case red case yellow case green } func action(for light: TrafficLight) -> String { switch light { case .red: return "Stop" case .yellow: return "Get Ready" case .green: return "Go" } } let currentLight = TrafficLight.yellow print(action(for: currentLight))
Enums improve code safety by limiting possible values.
Using switch with enums helps handle all cases explicitly.
Associated values let you store extra info with each case.
Enums group related values clearly and safely.
They help avoid invalid values and bugs.
Enums with associated values add flexibility.
enum Result {
case success(String)
case failure(String)
}
let outcome = Result.success("Done")
switch outcome {
case .success(let message):
print("Success: \(message)")
case .failure(let error):
print("Failure: \(error)")
}enum Status {
case ready
case waiting
case error(String)
}
let current = Status.error
print(current)Response? enum Response {
case data(String)
case error(Int, String)
}
let reply = Response.error(404, "Not Found")Pass the test and this pattern moves unknown