Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

missing return in closure expectet to return 'Void?'

Tags:

swift

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?

like image 618
Bartosz Jarosz Avatar asked Jul 27 '26 08:07

Bartosz Jarosz


2 Answers

You need to remove the optional value for Void

This

@escaping ((Int) -> Void)

or

@escaping ((Int) -> ())

in place of

@escaping ((Int) -> Void?)
like image 122
93sauu Avatar answered Jul 30 '26 09:07

93sauu


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.

like image 36
Daniel Arden Avatar answered Jul 30 '26 08:07

Daniel Arden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!