Search Your Question

What is @escaping and @nonescaping in swfit?

Ans : 

Closure : Closure are self contained blocks of functionality that can be passed around and used in code.


In swift 1.x and 2.x, closure parameter is @escaping by default. It means closure can be escape during function body execution. If don't want to escape, we have to mention @nonescaping as parameter.

In swift 3.x and after, closure parameter is @nonescaping by default.
Life cycle of non-escaping closure
Basically, a non-escape closure can only run the contents inside of it’s body, anything outside of it’s closure cannot be used. A non-escape closure tells the complier that the closure you pass in will be executed within the body of that function and nowhere else. When the function ends, the closure will no longer exist in memory. For example, if we needed to extract any values within our closure to be used outside of it, we may not do so. During the earlier days of Swift, closure parameters were escaping by default. Due to better memory management and optimizations, Swift has changed all closures to be non-escaping by default.

var closuresArray: [() -> Void] = []
func doClosures(completion: () -> Void){
completionHandlers.append(completion)
}
//ERROR!!!
passing non-escaping parameter 'completion' to function expecting an @escaping closure

Here is an example of an non-escaping closure. Here we have an empty array of closure and a function that includes a closure. If we were to append the closure in the function to the array of closure, we cannot do so because it is defaulted to non-escape. One great thing about Xcode is that it will that you that you need an escaping closure and can implement it for you.
Escaping Closure : 
Essentially escaping closure is the opposite of non-escaping closure. An escaping closure grants the ability of the closure to outlive the function and can be stored elsewhere. By using escape closure, the closure will have existence in memory until all of it’s content have been executed. To implement escaping closure, all we have to do is put @escaping in front of our closure. If you are unsure whether your closure needs escaping, no worries, as I’ve said before the complier is smart enough to let you know.
There are several ways when we need to implement an escaping closure. One instance is when we use asynchronous execution. When we are dealing with dispatch queue, the queue will hold onto the closure for you, and when the queue is done completing its work, then it will return back to the closure and complete it. Since dispatch queue is outside of the scope, we need to use escaping closure. Another instance is when we need to store our closure to a global variable, property, or any bit of storage that lives on past the function.

Always remember to use weak self while using a closure.

No comments:

Post a Comment

Thanks