CODEX
Understand Swift Autoclosures
Learn what the mysterious @autoclosure is and how to use it in Swift.
Autoclosures in Swift
An autoclosure works by wrapping a function argument in a closure. An autoclosure itself does not accept arguments. When an autoclosure is called, it returns the value of the expression wrapped inside of it.
Before diving any deeper let’s see what Apple Developer Docs says about autoclosures:
It’s common to call functions that take autoclosures, but it’s not common to implement that kind of function.
Overusing autoclosures can make your code hard to understand. The context and function name should make it clear that evaluation is being deferred.
This highlights the fact that autoclosures are rarely that beneficial and most of the time you should not implement functions using them. However, they can be useful in some very specific cases.
What’s the Benefit of an Autoclosure
On rare occasions, it is syntactically convenient to use an autoclosure when working with a function that takes a closure argument. This is because using an autoclosure allows you to omit curly braces, {}
.