What is the autoclosure attribute? - free Swift example code and tips
The @autoclosure attribute can be applied to a closure parameter for a function, and automatically creates a closure from an expression you pass in. When you call a function that uses this attribute, the code you write isn't a closure, but it becomes a closure, which can be a bit confusing – even the official Swift reference guide warns that overusing autoclosures makes your code harder to understand. To help you understand how it works, here's a trivial example: That code creates a printTest() method, which accepts a closure and calls it. As you can see, the print("Hello") is inside a closure that gets called between "Before" and "After", so the final output is "Before", "Hello", "After". If we used @autoclosure instead, it would allow us to rewrite the printTest() call so that it doesn't need braces, like this: These two pieces of code produce identical results thanks to @autoclosure. In the second code example, the print("Hello") won't be executed immediately because it gets wrapped
Explore this link on the map →