Enumerations
Enumerations, or enums, are a way to define a common type for a group of related values and enable you to work with those values in a type-safe way within your code. They are particularly useful when you have a fixed set of related options, such as days of the week, directions, or states of a system.
Defining Enumerations
In Swift, you define an enumeration using the enum keyword. Here’s a simple example:
enum CompassPoint {
case north
case south
case east
case west
}In this example, CompassPoint defines four possible directions.
Usage
You can create and assign values of this enum type like this:
var direction = CompassPoint.north
direction = .southThe type of direction is inferred as CompassPoint when it is first assigned a value.
Associated Values
Sometimes, it’s useful to be able to store associated values of different types alongside these enum cases. This additional information can vary each time you use that case as a value in your code.
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}You can then create instances of Barcode like this:
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")Raw Values
Enums can also come pre-populated with default values, called raw values, which are all of the same type. You define these raw values when the enum is first declared.
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}In this example, Planet.mercury has a raw value of 1, Planet.venus has a raw value of 2, and so on.
Accessing Raw Values
You can access the raw value of an enum case using the rawValue property:
let earthOrder = Planet.earth.rawValue // 3Initializing from Raw Value
If you have an enum with raw values you automatically get an initializer that takes the raw value and returns either the enumeration case or nil (If you pass an invalid raw value):
let possiblePlanet = Planet(rawValue: 3) // Planet.earth
let possiblePlanet = Planet(rawValue: 10) // nilMethods in Enumerations
Enumerations can also define instance methods that provide functionality related to the values of the enumeration:
enum CompassPoint {
case north, south, east, west
func description() -> String {
switch self {
case .north:
return "North"
case .south:
return "South"
case .east:
return "East"
case .west:
return "West"
}
}
}
let direction = CompassPoint.west
print(direction.description()) // "West"Enumerations and Switch Statements
Enums work particularly well with switch statements, enabling you to match individual enum cases against specific values:
let direction = CompassPoint.east
switch direction {
case .north:
print("Heading North")
case .south:
print("Heading South")
case .east:
print("Heading East")
case .west:
print("Heading West")
}This switch must be exhaustive, covering all possible cases of the enum.
Advanced Enumeration Features
Swift enumerations support additional features that make them even more powerful:
- Recursive Enumerations: An enumeration can have another instance of itself as the associated value for one or more of its cases.
enum ArithmeticExpression {
case number(Int)
indirect case addition(ArithmeticExpression, ArithmeticExpression)
indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}- Custom Initializers: Enumerations can define custom initializers to initialize the enum instance with a particular case.
enum Temperature {
case celsius(Double)
case fahrenheit(Double)
init(fromKelvin kelvin: Double) {
self = .celsius(kelvin - 273.15)
}
}Conclusion
Enumerations in Swift are a powerful feature that allows for clean, readable, and type-safe code. They can store additional information using associated values, can be initialized with raw values, and can include methods to add functionality directly within the enum. Understanding and utilizing enums effectively can greatly enhance the robustness and maintainability of your Swift code.
By leveraging the full potential of Swift enumerations, you can write code that is both expressive and efficient. Whether you’re dealing with fixed sets of related values or complex state management, Swift enums are a valuable tool in your programming toolkit. Happy Coding!