DEV Community

Cover image for escaping and non-escaping closure in Swift
NalineeR
NalineeR

Posted on • Edited on

2

escaping and non-escaping closure in Swift

In swift closures are of two types - escaping and non-escaping.

1.non-escaping - This is the default type of closure. This indicates that in function the control will not be back once gone.

func sumOfInt(a:Int,b:Int,handler:((Int)->())){
        let c = a + b
        handler(c)
 }
Enter fullscreen mode Exit fullscreen mode

Above function takes two integer parameters and returns the sum in the handler.
Here the control will be gone after executing the line handler(c) and won't be back.

2.@escaping - In this type of closure control returns to function even after code block has been executed. For example the url session tasks. In this type the local properties are accessible even when the control is back hence to capture them we need to mark the closure as @escaping to notify swift.

func sumWithDelay(a:Int,b:Int,handler:@escaping((Int)->())){
        let c = a + b
        DispatchQueue.main.asyncAfter(deadline: .now()+1) {
            handler(c)
            //control comes back in given duration
        }
        //control will be gone
}
Enter fullscreen mode Exit fullscreen mode

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools 🔁

Top comments (0)

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more