Swift version: 5.2
Closures and functions are very similar in Swift, but there are some subtle differences. When you’re learning, it’s easiest to think of a closure as being a function that doesn’t have a name of its own, and captures any values from its environment.
Nested functions – functions inside other functions – also capture values from their environment, but they have a name. As for global functions – functions that aren’t inside another function or type – they are also like closures, except they have a name and don’t capture values from their environment. Like I said, the differences are subtle!
Helpfully, Swift completely blurs the lines between functions, methods, operators, and closures, allowing us to use them interchangeably as long as they accept and return the correct types of data.
SPONSORED Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.
Available from iOS 8.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.