Swift version: 5.0
If you're here because you find closures hard, that's OK: most people find closures hard. But in truth, closures aren't actually that complicated, so I hope I can explain them to you quickly and easily.
Here's my best, simplest definition: a closure is a kind of anonymous function that gets stored as a variable so it can be called later on, and has the special ability to remember the state of your program when you used it.
myCode. Whoever is storing the closure (normally one of Apple's libraries) can then "call" that variable to run your closure's code.
The truth is that you've probably used closures without realizing it. Even a simple UIView animation call uses closures for the animations, and optionally also for the completion block. Just think of it as a chunk of code that gets called later on, and you're most of the way there.
SPONSOR Tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize your debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically. It only takes a line of code to setup. Get started for free.
Available from iOS 7.0
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.