0
0
Swiftprogramming~5 mins

Raw values for enums in Swift

Choose your learning style9 modes available
Introduction

Raw values let you give each option in an enum a fixed, simple value like a number or a word. This helps you connect enum options to real data easily.

When you want to assign a specific number or string to each choice in a list.
When you need to save or load enum values from files or databases.
When you want to compare enum options with simple values.
When you want to print or show enum options as readable text.
When you want to convert between enum options and their raw values quickly.
Syntax
Swift
enum EnumName: RawValueType {
    case option1 = rawValue1
    case option2 = rawValue2
    // more cases
}

The RawValueType can be Int, String, or other simple types.

Each case must have a unique raw value of the specified type.

Examples
Each direction has a short string as its raw value.
Swift
enum Direction: String {
    case north = "N"
    case south = "S"
    case east = "E"
    case west = "W"
}
Raw values start at 1 for Monday and automatically increase by 1 for the next days.
Swift
enum Weekday: Int {
    case monday = 1
    case tuesday
    case wednesday
    case thursday
    case friday
}
Sample Program

This program shows how to get the raw value from an enum case and how to create an enum case from a raw value.

Swift
enum Fruit: String {
    case apple = "A"
    case banana = "B"
    case cherry = "C"
}

let favorite = Fruit.banana
print("My favorite fruit raw value is \(favorite.rawValue)")

if let fruitFromRaw = Fruit(rawValue: "C") {
    print("Fruit from raw value 'C' is \(fruitFromRaw.rawValue)")
} else {
    print("No fruit found for that raw value")
}
OutputSuccess
Important Notes

You can create an enum case from a raw value using the initializer EnumName(rawValue: value). It returns an optional because the raw value might not match any case.

If you don't assign raw values explicitly for Int enums, Swift assigns them starting from 0 by default.

Summary

Raw values give enum cases fixed simple values like strings or numbers.

They help convert between enum cases and data easily.

Use raw values when you want to save, compare, or display enum options clearly.