Swift Raw Values
Introduction
In Swift, enumerations are first-class types that can define common types of related values together. While basic enumerations assign named values, Swift provides additional functionality through raw values - underlying values of specific types assigned to each enumeration case.
Raw values allow you to associate fixed values of a specific type (like Int
, String
, Character
, or Double
) to enum cases, making enums more powerful and versatile. This feature is particularly useful when working with data from external sources or when an enum needs to represent specific underlying values.
Understanding Raw Values
What Are Raw Values?
Raw values are underlying values of a specific type that you assign to enumeration cases. Think of them as pre-populated values that remain constant for a particular case of an enum.
Key Characteristics
- Each raw value must be unique within the enum
- Raw values are determined at compile-time (not runtime)
- All cases must have raw values of the same type
- Common raw value types include
Int
,String
,Character
, andDouble
Declaring Enums with Raw Values
To declare an enum with raw values, specify the raw value type after the enum name:
enum Direction: String {
case north = "NORTH"
case south = "SOUTH"
case east = "EAST"
case west = "WEST"
}
In this example, each case in the Direction
enum has a String
raw value.
Automatic Raw Value Assignment
Swift can automatically assign raw values in certain cases:
Integer Raw Values
When using Int
as the raw value type, Swift automatically assigns values starting from 0:
enum Planet: Int {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
// Raw values are automatically assigned as:
// mercury = 0, venus = 1, earth = 2, mars = 3, etc.
print(Planet.earth.rawValue) // Output: 2
You can also specify a starting value, and Swift will automatically increment for the remaining cases:
enum BitwiseOperation: Int {
case and = 0
case or = 1
case xor = 2
case leftShift = 3
case rightShift = 4
}
// Raw values are explicitly assigned
String Raw Values
When using String
as the raw value type, Swift uses the case name as the default raw value:
enum CompassPoint: String {
case north, south, east, west
}
print(CompassPoint.north.rawValue) // Output: "north"
Of course, you can explicitly assign string values when needed:
enum HTTPMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
print(HTTPMethod.post.rawValue) // Output: "POST"