Swift version: 5.10
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.
Some detail:
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.
GO FURTHER, FASTER Unleash your full potential as a Swift developer with the all-new Swift Career Accelerator: the most comprehensive, career-transforming learning resource ever created for iOS development. Whether you’re just starting out, looking to land your first job, or aiming to become a lead developer, this program offers everything you need to level up – from mastering Swift’s latest features to conquering interview questions and building robust portfolios.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 7.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.