Closure (with default value) as function parameter

Thanks to the wonders of Swift, we can:

func someFunction(someParameter: someType, someOtherParameter: someOtherType)

      

Let's call it like this:

someFunction(x, y)

      

We also have this:

func someFunction(someParameter: someType, someOtherParameter: someOtherType?)

      

We can call it like this:

someFunc(x, y)

      

OR

someFunc(x, nil)

      

However, this zero looks "ugly". Not to mention, we will have several optional parameters: it will look like

someFunc(x, nil, nil, nil,...etc)

      

Horror...

So, we can write this instead:

func someFunction(someParameter: someType, someOtherParameter: someOtherType? = nil)

      

Now we can say:

someFunction(x, y)

      

OR

someFunction(x)

      

Now ... problem: I want all of the above mechanics, but "y" should be a closure. The dead is simple. No input parameters, no return type. Type () → (). I also want it to be optional (I can provide it, or I can't) and I want it to be initialized with nil so that I can omit that parameter entirely if I don't have a closure to provide.

So: I would like to be able to say

someFunction(x, { ... }) 

      

OR

someFunction(x)

      

To that end, I declare it like this:

func someFunction(someParameter: someType, completionClosure: @escaping () -> ()? = nil)

      

However, the compiler won't have this. It basically says:

enter image description here

What's happening?




Locked topic ---> duplicate

Nil cannot be assigned to type () -> ()?

Swift 3 shortcut close option

But the former have remained largely unanswered / unresolved, while the latter seems to revolve mainly around @escaping issues.

This thread's question is about () → ()? = nil part. Simply removing @escaping as suggested in the second doesn't solve the problem; in fact it introduces a new one:

enter image description here

As suggested by another colleague, the issue was solved with @autoclosure.

func someFunction(someParameter: someType, completionClosure: @escaping @autoclosure () -> ()? = nil)

      

It now builds / works as expected.

I do not claim to fully understand HOW @autoclosure solves the problem (even after my colleague explained and after my own research, I already provided ... well ... closure ... why rely on autogeneration alone ... ), but now I'm forced to move on to developing a function. I will come back to this sometime in the future. Meanwhile, if others can light up the light, please do not hesitate.

+1


source to share





All Articles