NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

What the heck are closures and why does Swift love them so much?

Paul Hudson    @twostraws   

Updated for Xcode 12.0

Go on, admit it: you asked yourself exactly this question. If you didn’t I’d be surprised, because closures are one of the most powerful features of Swift but also easily the feature that confuses people.

So, if you’re sitting here thinking “wow, closures are really hard”, don’t be dismayed – they are hard, and you finding them hard just means your brain is operating correctly.

One of the most common reasons for closures in Swift is to store functionality – to be able to say “here’s some work I want you to do at some point, but not necessarily now.” Some examples:

  1. Running some code after a delay.
  2. Running some code after an animation has finished.
  3. Running some code when a download has finished.
  4. Running some code when a user has selected an option from your menu.

Closures let us wrap up some functionality in a single variable, then store that somewhere. We can also return it from a function, and store the closure somewhere else.

When you’re learning, closures are a little hard to read – particularly when they accept and/or return their own parameters. But that’s OK: take small steps, and backtrack if you get stuck, and you’ll be fine.

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Ever ask for help and your reviewer immediately notices issues you missed? Fernando Olivares is a 10-year veteran from Big Nerd Ranch and Lambda School who can help hone your app building skills, and he's just launched a new book that does just that – use the code "hacking" to save $5!

Buy the book

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

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!

Average rating: 4.1/5

Link copied to your pasteboard.