Accessing the enum defined inside the function

Overview:

I have an enum EngineError defined inside the function startEngine.

Question:

  • Is there a way to access EngineError outside of the function?
  • If so how?

Code:

struct Car {
    func startEngine() throws {
        enum EngineError: Error {
            case noFuel
        }
        throw EngineError.noFuel
    }
}

func f1() {
    let c1 = Car()

   //I would like to access EngineError here to handle the different errors
}

I wish I had better news for you, but no.

Among other restrictions, I think of a function like an instance of a non-extendable type defined with callAsFunction, whose members are all private. There is no way to raise their visibility.

For most cases, I don't really care, or that's exactly what I want. But as you've demonstrated, sometimes you're only going to throw a type of error from one non-overloaded, non-generic method. Being able to give that type one of the existing access modifiers would be nice for organization.

1 Like

@anon9791410 Thanks a lot for that clear explanation

You can access the private type via protocol conformance. Just for fun...

protocol Baz: Error {
    var isBaz: Bool { get }
}

func test() throws {
    struct Err: Baz {
        var isBaz: Bool { true }
    }
    throw Err()
}

do {
    try test()
} catch {
    if let b = error as? Baz, b.isBaz {
        print("hit")
    }
}
3 Likes

@jazzbox Thanks a lot, that is an interesting way, I didn't think that far, I guess in my example, every case would have to conform to a different protocol (which might not be possible)