Menu
Coddy logo textTech

Enums with Methods

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 15 of 57.

An enum defines a type with a fixed set of cases. Values are written with a dot, and switch must handle every case, so adding a case later shows every place that needs updating:

enum Direction {
    case north, east, south, west
}

let heading = Direction.east
switch heading {
case .north: print("up")
case .east: print("right")
case .south: print("down")
case .west: print("left")
}

Output:

right

Enums can have methods and computed properties. Inside them, self is the current case:

enum Direction {
    case north, east, south, west

    var turnedRight: Direction {
        switch self {
        case .north: return .east
        case .east: return .south
        case .south: return .west
        case .west: return .north
        }
    }
}

print(Direction.north.turnedRight)
print(Direction.west.turnedRight.turnedRight)

Output:

east
east

A raw value attaches a fixed value of one type to each case. init(rawValue:) goes the other way and returns nil when no case matches:

enum Size: String {
    case small = "S", medium = "M", large = "L"
}

print(Size.medium.rawValue)
print(Size(rawValue: "L") == .large)
print(Size(rawValue: "XL") == nil)

Output:

M
true
true

Associated values let each case carry its own data, which is how one type can hold differently shaped values. switch binds the data with let:

enum Payment {
    case cash(amount: Int)
    case card(number: String, amount: Int)

    var amount: Int {
        switch self {
        case .cash(let amount): return amount
        case .card(_, let amount): return amount
        }
    }
}

let payments: [Payment] = [.cash(amount: 20), .card(number: "4242", amount: 55)]
print(payments.map { $0.amount })

Output:

[20, 55]
challenge icon

Challenge

Easy

Complete the enum Command with the cases forward, back, left and right, backed by the raw values F, B, L and R. Add a computed property step that returns the change in position: forward 1, back -1, left and right 0. Then complete run(_:), which turns each character into a command with init(rawValue:) (skipping unknown characters) and returns position 2, turns 1, skipped 1.

The supplied code reads one line of command letters and prints the result of run(_:).

Your code goes in Command.swift and Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
print(run(input[0]))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Swift playground