Raw value enumerations are a powerful feature in Swift that allow you to associate default values with enumeration cases. These values can be strings, characters, or any integer or floating-point type.
To create a raw value enumeration, specify the type of the raw value after the enum name:
enum Compass: String {
case north = "N"
case south = "S"
case east = "E"
case west = "W"
}
In this example, we've created a Compass
enum with String
raw values.
Swift can automatically assign raw values in certain cases:
enum Planet: Int {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
print(Planet.earth.rawValue) // Outputs: 2
You can access the raw value of an enum case using the rawValue
property:
let earthDirection = Compass.east
print(earthDirection.rawValue) // Outputs: "E"
Raw value enums automatically receive an initializer that takes a raw value and returns an optional enum case:
if let planet = Planet(rawValue: 3) {
print("The fourth planet is \(planet)")
} else {
print("There is no planet with raw value 3")
}
When working with raw value enumerations, keep these points in mind:
To deepen your understanding of Swift enumerations, explore these related topics:
Raw value enumerations are a versatile tool in Swift programming. They provide a clean way to associate default values with enum cases, enhancing code readability and functionality.