Notice: Undefined index: understanding-swift in /var/sites/hackingwithswift.com/site/src/Controller/NewBooksReadController.php on line 89
Why does Swift have trailing closure syntax? - a free tutorial

NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

Why does Swift have trailing closure syntax?

Paul Hudson    @twostraws   

Trailing closure syntax is designed to make Swift code easier to read, although some prefer to avoid it.

Let’s start with a simple example first. Here’s a function that accepts a Double then a closure full of changes to make:

func animate(duration: Double, animations: () -> Void) {
    print("Starting a \(duration) second animation…")
    animations()
}

(In case you were wondering, that’s a simplified version of a real and very common UIKit function!)

We can call that function without a trailing closure like this:

animate(duration: 3, animations: {
    print("Fade out the image")
})

That’s very common. Many people don’t use trailing closures, and that’s OK. But many more Swift developers look at the }) at the end and wince a little – it isn’t pleasant.

Trailing closures allow us to clean that up, while also removing the animations parameter label. That same function call becomes this:

animate(duration: 3) {
    print("Fade out the image")
}

Trailing closures work best when their meaning is directly attached to the name of the function – you can see what the closure is doing because the function is called animate().

If you’re not sure whether to use trailing closures or not, my advice is to start using them everywhere. Once you’ve given them a month or two you’ll have enough usage to look back and decide more clearly, but hopefully you get used to them because they are really common in Swift!

Hacking with Swift is sponsored by ViRE

SPONSORED ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.

Download on the App Store

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.