Swift return statements and line breaks

Sep 10, 2014 · Follow on Twitter and Mastodon swift

I’m currently porting some iOS games from Objective-C to Swift. While doing this, I stumbled upon something interesting in how Swift handles return statements and new lines.

When I tried to temporarily disable the logic of a function, by adding a return statement topmost in the function body, I noticed that it didn’t work the way I expected it to.

func doStuff() {
   return
   print("Doing some stuff")   
   //Some code for animating the hand
}

Turns out that unlike Objective-C, Swift doesn’t abort after the return statement, but rather returns the result of the second line of code.

I thought that the return statement would immediately end all execution, but it turns out that this isn’t the case with Swift. Something to be aware of.

Discussions

Please share any ideas, feedback or comments you may have in the Disqus section below, or by replying on Twitter or Mastodon..

Follow for more

If you found this interesting, follow the Twitter and Mastodon accounts for more content like this, and to be notified when new content is published.