An enumeration (enum) defines a common type for a group of related values.
Enums allow you to work with those values in a type-safe way within your code.
Swift enumerations are much more powerful than in languages like C, offering features like associated values and pattern matching.
You introduce an enumeration with the enum keyword and place its entire definition within a pair of braces.
Each possible value inside the enum is declared using the case keyword.
enum CompassPoint {
case north
case south
case east
case west
}
var direction = CompassPoint.north
// Once inferred, you can use the dot syntax
direction = .south
print(direction)
Unlike C, Swift enum cases do not automatically have integer values set to them (like 0, 1, 2, etc.).
You can match individual enum values with a switch statement.
This is highly effective because Swift switch statements must be exhaustive.
If you forget to handle an enum case, your code will refuse to compile!
enum CompassPoint {
case north
case south
case east
case west
}
let currentDirection = CompassPoint.east
switch currentDirection {
case .north:
print("Heading North!")
case .south:
print("Heading South!")
case .east:
print("Heading East!")
case .west:
print("Heading West!")
}
One of the greatest features of Swift enums is the ability to attach extra information to an enum case.
This extra information is called an "Associated Value", and different cases can store completely different types of data.
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
var productCode = Barcode.upc(8, 85909, 51226, 3)
productCode = .qrCode("ABCDEFGHIJKLMNOP")
switch productCode {
case .upc(let numberSystem, let manufacturer, let product, let check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
print("QR code: \(productCode).")
}
This allows an enum to act almost like a lightweight, highly specific object.
Do Swift enum cases automatically default to integer values (0, 1, 2, etc.) like in C?