David Cordero

Swift: Avoid auto return in closures

Published on 06 Dec 2014

In Swift, you have several options for writing closures more concisely.

When a closure’s type is already known, such as the callback for a delegate, you can omit the type of its parameters, its return type, or both. Single statement closures implicitly return the value of their only statement.

Because of this feature, We can create super neat closures like the following one:

let sortedNumbers = sorted(numbers) { $0 > $1 }

But sometimes, when we are not looking for a functional programming solution, it is a pity to deal with this implicit return.

For example when we only want to call a single function from our closure:

func someFunctionThatReturnSomething () -> Bool {
    return true

func someFunctionThatTakesAClosure ( closure: Void -> Void) {}

// As it has a single line it FAILS because it tries to return the result of someFunctionThatReturnSomething, which is not Void
someFunctionThatTakesAClosure( {
        someFunctionThatReturnSomething() // Compilation error

To deal with this issue we have a couple options:

Solution 1: Add an explicit return

someFunctionThatTakesAClosure( {

Solution 2: Ignore the result from someFunctionThatReturnSomething

someFunctionThatTakesAClosure( {
    _ = someFunctionThatReturnSomething()

Although I honestly don’t like any of both solutions, I prefer the second solution since it keeps the concise style of Swift and makes it clear that you are purposefully and knowingly ignoring the return value from the function.

This implicit return is definitely creating more pain than goodness.

⚠️Update: Swift 1.2

This is not longer an issue with the new version 1.2 of Swift. As it is described in the releases notes:

Unannotated single-expression closures with non-Void return types can now be used in Void contexts.