Swift version: 5.6
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:
func printTest1(_ result: () -> Void) {
print("Before")
result()
print("After")
}
printTest1({ print("Hello") })
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:
func printTest2(_ result: @autoclosure () -> Void) {
print("Before")
result()
print("After")
}
printTest2(print("Hello"))
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 inside a closure for execution later.
The @autoclosure
attribute is used inside Swift wherever code needs to be passed in and executed only if conditions are right. For example, the &&
operator uses @autoclosure
to allow short-circuit evaluation, and the assert()
function uses it so that the assertion isn’t checked outside of debug mode.
SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 8.0 – learn more in my book Pro Swift
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.