Closure (with default value) as function parameter [duplicate]

妖精的绣舞 提交于 2019-12-08 03:36:53

问题


Thanks to the marvels of Swift, we can have:

func someFunction(someParameter: someType, someOtherParameter: someOtherType)

We call it like so:

someFunction(x, y)

We also have this:

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

We may call this like so:

someFunc(x, y)

OR

someFunc(x, nil)

However, that nil looks "ugly" there. Not to mention if we would have multiple optional parameters: it would 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 nicely say:

someFunction(x, y)

OR

someFunction(x)

Now...the problem: I want all of the above mechanics but "y" must be a closure. A dead_simple one. No input parameters, no return type. The () -> () kind. I also want it to be optional (I may provide it or I may not), and I want it to be initialised with nil so that I can totally omit that parameter if I have no closure to provide.

So: I would like to be able to say

someFunction(x, { ... }) 

OR

someFunction(x)

To that end, I declare it like so:

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

However, the compiler won't have any of that. Basically it says:

What's going on?




The topic was closed ---> duplicate of

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

Swift 3 optional escaping closure parameter

But the first remained mostly unanswered / unresolved while the second seems to revolve mainly around @escaping issues.

The issue of this topic is about the () -> ()? = nil part. Simply removing @escaping, as suggested in the second, does not solve the problem; it introduces a new one in fact:

At the suggestion of another colleague, the problem was solved with the help of an @autoclosure.

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

Now it builds / runs as expected.

I don't claim I fully understand HOW @autoclosure solves the problem (even after my colleague's explaining and after my own research; I already provided a...well...closure...why rely on a auto generated one...), but right now I'm forced to move on with the feature development. I'll come back to this sometime in the future. In the meanwhile, if others can shine a light on it, please feel free.

来源:https://stackoverflow.com/questions/43652771/closure-with-default-value-as-function-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!