TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Checkpoint 6 using Error enum

Forums > 100 Days of SwiftUI

Howdy everyone. I've been looking at other solutions to this and am loving the various approaches people are coming up with.

I tried to do checkpoint 6 using an Error enum to reject a gear change which is out of range. In order to make the error message a little bit more contextual, I added an associated value to the enum but I don't know how to get at this associated value in the catch{} block.

Here's what I've got at the moment

import UIKit

enum CarError: Error {
    case gearNotAvailable (gear: Int)
}

struct Car {
    let numberOfGears: Int
    private(set) var currentGear: Int = 0 // 0=Neutral, -1=Reverse

    mutating func changeGear(newGear: Int) throws {
        if newGear < -1 || newGear > numberOfGears {
            throw CarError.gearNotAvailable(gear: newGear)
        }
        currentGear = newGear
        print("The car is now in gear \(currentGear)")
    }
}

var car = Car(numberOfGears: 3)

do {
    try car.changeGear(newGear: 3)
    try car.changeGear(newGear: 5)
} catch CarError.gearNotAvailable {
    print("You tried to change to a gear \(CarError.gearNotAvailable) which the car does not have")
}

The error message comes back as:

You tried to change to a gear (Function) which the car does not have

I'm struggling to find any examples online showing how to extract associated values from an error enum in a catch block. Is there a simple way to get at this value or is the solution going to be more convoluted than I imagined?

2      

Hi! This should do the trick.

do {
    try car.changeGear(newGear: 3)
    try car.changeGear(newGear: 5)
} catch CarError.gearNotAvailable(let gear) {
    print("You tried to change to a gear \(gear) which the car does not have")
}

2      

Fantastic! Many thanks :)

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.