DEV Community

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

Posted on • Edited on

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

Top comments (0)