NEW! Master Swift design patterns with my latest book! >>

What is the autoclosure attribute?

Paul Hudson       @twostraws

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 printTest(_ result: () -> Void) {
    print("Before")
    result()
    print("After")
}

printTest({ 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 printTest(_ result: @autoclosure () -> Void) {
    print("Before")
    result()
    print("After")
}

printTest(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.

Available from iOS 8.0 – learn more in my book Pro Swift

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Learn Swift faster!

Take your Swift learning to the next level: buy the Hacking with Swift e-book and get bonus material to help you learn faster!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>