TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Implicit returns from single-expression functions

Available from Swift 5.1

Paul Hudson      @twostraws

SE-0255 has removed a small but important inconsistency in the language: single-expression functions that return a value can now remove the return keyword and Swift will understand it implicitly.

In previous versions of Swift, single-line closures that returned a value you could omit the return keyword because the only line of code that was there must be the one that returned a value. So, these two pieces of code were identical:

let doubled1 = [1, 2, 3].map { $0 * 2 }
let doubled2 = [1, 2, 3].map { return $0 * 2 }

In Swift 5.1, this behavior has now been extended to functions as well: if they contain a single expression – effectively a single piece of code that evaluates to a value – then you can leave off the return keyword, like this:

func double(_ number: Int) -> Int {
    number * 2
}

That will probably cause some people to do a double take at first, but I’m sure it will become second nature over time.

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Other changes in Swift 5.1…

Download all Swift 5.1 changes as a playground Link to Swift 5.1 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.