Learn Closure in Swift, Escaping vs Non-Escaping Closure

Ignatio Julian
3 min readOct 20, 2021

--

Pararrel Task

as iOS Developer maybe familiar with this and maybe for some new developers still confused what is it and how to work with it. In this article I would share how to use and how closure works in Swift.

First of all, I would to talk about what Closure it is. From Swift Documentation, Closure are self-contained blocks of functionality that can be passed around and used in your code. Closure can capture and store references to any constants and variable from the context in which they’re defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.

So what does the above statement mean? Let me help you to understand deeply with simple example.

I want to create a function which adds two numbers and return the value. the first example will use the regular function.

Regular Function

Here i create a function and collect num1 and num2 as parameters and expect the return value is Int. As always create variable to collect result and collect logic and then call the function in order to get the value. So we’re moving to how Closure it is.

Closure

From the code above we see the difference between using closures and regular functions.
we declare the variable as it were a function then write the parameters and fill in the logic. From the comparison of the code above the way of calling is also different. Normal functions use parameter names while closures don’t.

So now I hope you understand more about closures 🥳. let’s move to Escaping and Non-Escaping Closure.

Escaping Closure is Asynchronous and Non-Escaping Closure is Synchronous. To make easier, I already prepare some code as example.

Non-Escaping Closure

I create function it’s called nonEscapingClosure and create results it’s going to be accept String and return Void. We see the result that the closure block run synchronously. When we call the closure block it means they prioritize what inside the block then continue to outside the block. Once the completion is called then ‘next closure’ run after nonEscapingClosure is called. This pattern run step-by-step by what would be executed. Let’s move to Escaping Closure.

Escaping Closure

First we see on log results. I create similar function that contains same parameter with nonEscapingClosure. You can clearly understand by where the Closure is declare and go to end closure then immediately it’s goes for the next line of the code and the last execution is runing the results after waiting for 3 seconds. Or you can use DispatchQueue.main.async for run executed first.

So thats all introduction about Closure in Swift, how we used it and the difference between non-escaping Closure and escaping Closure. I hope this simple article make great impact to you and feel free to give feedback. Happy Coding and keep going! 🥳

--

--