Swift Enums Example

1. Introduction

Enums, or enumerations, are a powerful feature in Swift that allow you to define a common type for a group of related values, ensuring that you use these values correctly in your code. They can have methods associated with them, and they can be provided with raw values or associated values, giving them added flexibility.

2. Source Code Example

// Defining an enum for compass directions
enum CompassDirection {
    case north
    case south
    case east
    case west

// Declaring a variable of type CompassDirection
var currentDirection = CompassDirection.west

// Using a switch statement to evaluate the enum value
switch currentDirection {
case .north:
    print("We are heading north!")
case .south:
    print("We are heading south!")
case .east:
    print("We are heading east!")
case .west:
    print("We are heading west!")

// Enum with raw values
enum Planet: Int {
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune

// Accessing the raw value
let earthsOrder = Planet.earth.rawValue
print("Earth is the \(earthsOrder)th planet from the sun.")

// Enum with associated values
enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)

var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")

switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
    print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
    print("QR code: \(productCode).")


We are heading west!
Earth is the 3rd planet from the sun.

3. Step By Step Explanation

1. The CompassDirection enum represents the four main directions of a compass. We define a variable currentDirection of this enum type and use a switch statement to check its value.

2. The Planet enum demonstrates how enums can be given raw values. Here, each planet is given a raw value representing its order from the sun. This enum's raw type is Int, meaning each case is automatically assigned an integer.

3. The Barcode enum shows enums with associated values. This means each case can store different types of data. In our example, a UPC barcode stores four integers, while a QR code stores a string. When we evaluate the value with a switch statement, we can extract these associated values for use in our code.