What are closures?
As per apple documentation, closures are self contained blocks of functionality that can be passed around code. In swift these are similar to what we called blocks in objective c and lambda in other languages. The definition is quiet complex to understand, so in simple words we can define closure as a chuck of code that can perform certain functionality or calculations and then pass the control to the class from where its getting called or invoked, like a callback.
Example of closures are completionHandlers we often used while making an API request. So in this tutorial we will learn how to write closures in swift, before we start learning how to write closures, we must knew how to write function (i hope you are aware of syntax to create a function), if you are novice and learning swift then below is the code snippet for the same
Difference between function and closure
1. Closures don’t have func keyword
2. Closures don’t have name
3. Closures have in keyword (function don’t have)
At this point we knows the difference between a function and closure, so let us make our function a closure.
Step 1: Remove ‘func’ keyword from our function and name ‘welcomeGuest’ also removed. We satisfied two conditions of closure that it doesn’t contain ‘func’ keyword and name. Our closure will look like
Step 2: Third point tells us that closure has ‘in‘ keyword, so we need to place ‘in’ keyword in place of opening curly brace of and move that open curly brace to start of the closure. Our code will look like
Step 3: At this point compiler is showing you an error “expected declaration”, so in order to remove error, we need to assign the closure to a variable, as shown in below code snippet
Step 4: We are done with closures as we successfully write a closure that returning a string value. In order to call our closure inside viewDidLoad function as shown below
Where to go from here:
In this tutorial, we learned how to write closures in swift, We learned about difference between closure and function and how to write closure in swift and use them in our code. If you have question, please feel free to ask.