Why do we need to use closure? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Why do we need to use closure?

25th Aug 2016, 2:19 PM
Aung Thuya
Aung Thuya - avatar
1 Answer
+ 5
Closure (also often referred to anonymous function because it doesn't have a declared name) lets you package a particular functionality and have another function executes it. It cannot be invoked by calling it directly because it's never declared thus has no name. Closure is often used as an argument to a declared function that takes a closure as an argument meaning the closure will be executed just before the end of the execution of that declared function. So for example, take a look at documentation for a UIViewController instance method called presentViewController:animated:completion. The external parameter animated takes in a bool value and the external name completion takes a closure. So instead of declaring (naming a function) somewhere in the class where that instance method is called, you can just dump the closure as the last argument. I hope it helps.
29th Aug 2016, 5:04 AM
swifty