missing return in closure expectet to return 'Void?'

Viewed 1480

I have a problem that I can't understand, I have completion handler that returns Void?

_ completionHandler: @escaping ((Int) -> Void?)

and when I use it like this:

service.getItems({ val in
  row.hidden = Condition.init(booleanLiteral: val == 0)
  row.evaluateHidden()
})

xCode is showing an

Missing return in a closure expected to return 'Void?'

so I have to add

return nil

What is more, if I have only 1 line in closure I dont need to return (I'm assuming it treats that 1 line as return). Whats the point of returning nil in closure that returns nullable void? Is this a bug or some kind of swift feature I don't undertand?

2 Answers

You need to remove the optional value for Void

This

@escaping ((Int) -> Void)

or

@escaping ((Int) -> ())

in place of

@escaping ((Int) -> Void?)

In your closure a return type is specified (here it is Optional Void Void?), thus the compiler will always expect a return value as the outcome of the function or closure.

Since this is an optional Void Void? you still have to either return nil or return Void. In function/closure with return type of non optional Void (same as no return type f.e. here: func returnVoid() { /* do something */ } you do not have to write the return keyword explicitly, however compiler inserts it into the function anyway.

And yes, starting with Swift 5.1 you can omit the return keyword when there is only one expression. (Source)

As for your case, you could just change your completion handler to:

_ completionHandler: @escaping ((Int) -> Void) or the equivalent _ completionHandler: @escaping ((Int) -> ())

Optional Void Void? as the return type in your case seems not necessary.

Related