enum RawValue (Int / String)
Swift enums can have raw values (RawValue). By associating each case with a value such as an integer or string, you can convert between external data and enum cases.
Syntax
// Int RawValue
enum EnumName: Int {
case case1 = 1
case case2 = 2
case case3 // Automatically 3
}
// String RawValue
enum EnumName: String {
case case1 = "value1"
case case2 // The case name becomes the raw value
}
// Create an enum from a raw value (failable initializer)
let value = EnumName(rawValue: 1) // Optional<EnumName>
Properties and Methods
| Property / Method | Description |
|---|---|
| case.rawValue | Returns the raw value associated with the case. |
| init(rawValue:) | Creates an enum from a raw value. Returns nil if no matching case exists. |
Sample Code
// Int RawValue
enum Month: Int {
case january = 1, february, march, april
case may, june, july, august
case september, october, november, december
}
// Getting the raw value
print("March value: \(Month.march.rawValue)") // 3
print("December value: \(Month.december.rawValue)") // 12
// Creating an enum from a raw value
if let month = Month(rawValue: 7) {
print("Month number 7: \(month)")
}
// Returns nil if the value does not exist
let invalid = Month(rawValue: 13)
print("Number 13: \(invalid as Any)")
// String RawValue
enum Planet: String {
case mercury = "Mercury"
case venus = "Venus"
case earth = "Earth"
case mars = "Mars"
}
print(Planet.earth.rawValue) // Earth
// Case name becomes the raw value when no value is specified
enum Color: String, CaseIterable {
case red, green, blue
}
for color in Color.allCases {
print("\(color) → \(color.rawValue)")
}
Notes
Enums with raw values are useful for converting between database integer codes or API string codes and enum cases. For Int raw values, if no value is specified, Swift automatically assigns the previous case's value plus one.
init(rawValue:) is a failable initializer that returns nil when no matching case exists. Force-unwrapping a raw value with no corresponding case will cause a runtime crash.
For enums with associated values, see enum Associated Values.
If you find any errors or copyright issues, please contact us.