Start Coding

Topics

Swift Enumerations

Enumerations, often called enums, are a powerful feature in Swift that allow you to define a group of related values. They provide a way to work with named values in a type-safe manner.

Defining an Enumeration

To define an enum in Swift, use the enum keyword followed by the name of the enumeration and its cases:

enum CompassDirection {
    case north
    case south
    case east
    case west
}

You can also define multiple cases on a single line, separated by commas:

enum Planet {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}

Using Enumerations

To use an enum, you can create a variable or constant of that type and assign it one of the enum's cases:

var direction = CompassDirection.north
let homeWorld = Planet.earth

Swift's type inference allows you to omit the enum type when the context is clear:

direction = .south

Switch Statements with Enums

Enums work particularly well with Swift switch statements, ensuring you handle all cases:

switch direction {
case .north:
    print("Heading north")
case .south:
    print("Heading south")
case .east:
    print("Heading east")
case .west:
    print("Heading west")
}

Associated Values

Swift enums can also store associated values, allowing each case to have custom data types:

enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

let productBarcode = Barcode.upc(8, 85909, 51226, 3)

For more information on enums with associated values, check out the guide on Swift Associated Values.

Raw Values

Enums can have raw values, which are pre-populated values of a specific type:

enum ASCIIControlCharacter: Character {
    case tab = "\t"
    case lineFeed = "\n"
    case carriageReturn = "\r"
}

To learn more about raw value enumerations, visit the Swift Raw Value Enumerations guide.

Best Practices

  • Use enums to represent a fixed set of related options or states.
  • Name enum cases using lowerCamelCase.
  • Consider using associated values when you need to attach additional information to enum cases.
  • Utilize raw values when you need to work with underlying data types or interoperate with other languages.

Conclusion

Enumerations in Swift provide a powerful way to model and work with groups of related values. They enhance type safety, improve code readability, and integrate seamlessly with other Swift features like switch statements and type inference.