--

What is the real use for @autoclosure?

Thanks for the post Zafar! However, I think it doesn’t explain what @autoclosure really does and how it can be useful.

In your example you can pass functions directly as arguments: makeDecision(condition: true, actionTrue: action1, actionFalse: action2) without using @autoclosure.

Though, assume an action has a different set of parameters which are known beforehand: func action1(parameter: Int). Passing the function as an argument is no longer possible. What you can do is to wrap the call with a clojure: makeDecision(condition: true, actionTrue: { action1(parameter: 1) }, actionFalse: action2).

This is exactly what @autoclosure does for you automatically. Having the makeDecision function declared as in your example, you can now call it like this: makeDecision(condition: true, actionTrue: action1(parameter: 1), actionFalse: action2()), which is essentially the same as calling it like makeDecision(condition: true, actionTrue: { action1(parameter: 1) }, actionFalse: action2).

--

--

Nikita Lazarev-Zubov

Swift and general programming topics, Agile software development, soft skills