logoalt Hacker News

ninkendoyesterday at 1:09 PM3 repliesview on HN

EDIT: I don’t think you can actually put a return in a defer, I may have misremembered, it’s been several years. Disregard this comment chain.

It gets even better in swift, because you can put the return statement in the defer, creating a sort of named return value:

    func getInt() -> Int {
        let i: Int // declared but not
                   // defined yet!

        defer { return i }

        // all code paths must define i
        // exactly once, or it’s a compiler
        // error
        if foo() {
            i = 0
        } else {
            i = 1
        }

        doOtherStuff()
    }

Replies

kibwenyesterday at 2:32 PM

This control flow is wacky. Please never do this.

mojubayesterday at 1:24 PM

Huh, I didn't know about `return` in `defer`, but is it really useful?

show 2 replies