Enums define a group of related values in a type-safe way. They are particularly useful for defining states, options, or categories that a variable can have.
enum CompassPoint {
case north
case south
case east
case west
}
var direction = CompassPoint.north
switch direction {
case .north:
print("Heading North")
case .south:
print("Heading South")
case .east:
print("Heading East")
case .west:
print("Heading West")
}
//Output
print("Heading North")
Raw Values
Enums can have raw values associated with each case. The raw value must be of the same type and unique.
enum Planet: Int {
case mercury
case venus
case earth
case mars
}
print(Planet.mercury.rawValue)
// Output
0
enum Seasons: String {
case spring = "Blossoms"
case summer = "Heat"
case winter = "Snow"
}
print(Seasons.winter.rawValue)
// Outputs: Snow
Associated Values
Enums can store additional associated values for each case.
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
var productCode = Barcode.upc(8, 85909, 51226, 3)
switch productCode {
case .upc(let numberSystem, let manufacturer, let product, let checkDigit):
print("UPC: \(numberSystem)-\(manufacturer)-\(product)-\(checkDigit)")
case .qrCode(let code):
print("QR Code: \(code)")
}
//Output
UPC: 8-85909-51226-3
Enum with Function
enum TrafficLight {
case red, yellow, green
func action() -> String {
switch self {
case .red:
return "Stop"
case .yellow:
return "Get Ready"
case .green:
return "Go"
}
}
}
let light = TrafficLight.red
print(light.action())
// Output
Stop
Enum with CaseIterable
enum Beverage: CaseIterable {
case coffee, tea, juice
}
for beverage in Beverage.allCases {
print(beverage)
}
//Output
coffee
tea
juice