Updated for Xcode 14.2
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:
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.
SAVE 50% To celebrate WWDC23, 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.
Link copied to your pasteboard.