Omitting the return type in Swift closures

I'm working through one of the examples at the very handy and colourfully named site here, specifically :

func applyMutliplication(value: Int, multFunction: Int -> Int) -> Int {
  return multFunction(value)
}

applyMutliplication(2, {value in
  value * 3
})

Notice that the closure given when calling applyMultiplication() does not specify a return type. I would not expect that example to have worked but it does; the result is "6" using the example above. I would have thought a null value would be "returned". Or does Swift always return something unless you explicitly return null?

If I modify that closure to specify a return type then it continues working the same way as one would expect

let result = applyMultiplication(2, {value -> Int in 
  value * 3
})

Upvotes: 0

Views: 624

Answers (1)

Caleb
Caleb

Reputation: 125017

I would not expect that example to have worked but it does

In many cases, Swift can often infer types of variables and expressions. In this case, Swift looks at the value you're returning and can infer the type.

If I modify that closure to specify a return type then it continues working

Specifying the type explicitly doesn't change the type that's being returned, so there's no change in behavior.

Or does Swift always return something

Even a void function returns something -- it returns an empty tuple. As was pointed out in the comments, single expression closures implicitly return the value of their expression.

Upvotes: 0

Related Questions