"fallthrough" + "guard/else"

Can anybody please confirm, that this usage of "fallthrough" is eligible? :pray: (the code compiles)

extension URLRequest {
    init(url: URL, httpMethod: HTTPMethod, token: String? = nil) {
        switch httpMethod {
        case .post(let body), .put(let body?):
            guard let httpBody = try? body.encode() else { fallthrough }
            self.init(url, httpMethod.name, httpBody, "application/json", token)
        default:
            self.init(url, httpMethod.name, nil, nil, token)
        }
    }
}
1 Like

(EDITIED) It looks like the fallthrough here has nothing to do with guard/else here. fallthrough is used to jump to the next case block, and since it jumps out of the current context, guard/else accepts it (just like return in a func).

2 Likes

Late to this discussion, but I hope this helps someone:

I wound up on this year-old thread by searching the web for: “swift switch guard fallthrough”. Like most other information on the web (and like Apple’s documentation?) there’s very little in depth and exhaustive, just minimalist, for-beginners, simplest use cases only. (At least Apple’s pages aren't endless similar AI regurgitations, yet)

I was wondering the same thing as @RoBo-Inc. In my situation in a switch statement over the results of an alert’s runModal(), a case for the first button and a default for cancel. I wanted to verify that I could use guard / fallthrough in an error condition in the first case, it's something I'd never had the occasion to do before.

I don’t think “fallthrough here has nothing to do with guard/else here” is a helpful answer. The original question with respect to the two constructs is a valid one, if fallthrough was okay to use as control flow in the else clause of a guard for exiting the current scope, like break or return, etc.

And although it doesn't seem to be terribly explicit in the documentation or covered in many examples or discussions online, yes it's indeed okay to use fallthrough here, and that it does what you expect.

1 Like

It is worse than that. It lies!

That said, the original example is no good because the language doesn’t have do-catch expressions.

let httpBody = do { try body.encode() } catch { fallthrough }

Instead, it needs to resort to the Optional shoehorn above, or explicit typing. :-1:

let httpBody: HTTPBody; do { httpBody = try body.encode() } catch { fallthrough }
1 Like

Yes, fallthrough anywhere within a case will transfer control to the following case block.

1 Like