Clicky

iOS Dev Nugget 308 Careful with early return statements in functions that return void

.

Need to run a code review on your codebase? Hire me

Suppose you have code like this:

func foo() {
    print("foo called")
}

func bar() {
    print("bar called")

    foo()
    //Some more code here.
}

bar()

The output is:

bar called
foo called

All good. Now, during debugging, you want to skip running foo() and all the other code in bar(), so you might add an early return statement like this:

func bar() {
    print("bar called")

    return

    foo()
    //Some more code here.
}

Do you see the problem?

It'll still execute foo() because it will consider return foo() to be a single statement and then skip the rest of the code in bar(). The way to prevent this is to use return; (i.e. end it with a semi-colon) or just comment out the rest of the code.

This is easy to miss and I was bitten by this recently.

PS: The compiler issues a warning for this, but it's easy to miss while debugging and making all sorts of code changes quickly to figure out the problem at hand.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues