Swift Tutorials Difference between escaping and non escaping closures in swift 5.2 programming language with example

In this articles we are going to learn swift programming, the difference between escaping closures and non-escaping closures. 

According to the Apple Documentation, “Closures are self-contained blocks of functionality that can be passed around and used in your code”.

The concept of Swift Closure is similar to blocks in C. Closures are nameless functions and without the keywordfunc.

closures programing swift, closures swift tutorials


    • Escaping closures
    • Non-escaping closures

    Non-Escaping Closure:

    A closure is said to be non escaping when the closure is passed as an argument to the function and is called before the function returns. The closure is not used outside of the function. By default, all closures are non escaping closure.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
      override func viewDidLoad(){
          showArticles(noOfArticles: 40, closure: { url in
            print("Please visit my site \(url)")
          })
        }
        func showArticles(noOfArticles: Int, closure: (String) -> Void) {
          print("advanced development is here!")
          
          closure("www.appcodezip.com")
          
          print("Pls like the AppCodeZip")
        }

    When you run the above program, the output will be:

        advanced development is here!

        Please visit my site www.appcodezip.com

        Pls like the AppCodeZip

    In the above example, we just called the function with a closure that gets executed at the end of the function's body. Therefore, we are not escaping the execution of the closure. After finishing, the execution closure will have no existence in the memory. in that case, such closures are called non-escaping.

    Escaping Closure:

    A closure is said to escape a function when the closure is passed as an argument to the function but is called after the function returns or the closure is used outside of the body of the function.

    Let's modify the previous function a touch. Inside the showArticles function. We wrap the closure inside DispatchQueue.main.asyncAfter() in order that the closure are going to be executed five seconds after the present time. we'll also need to add @escaping here else Xcode will complain as Escaping closure captures non-escaping parameter 'closure'

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    override func viewDidLoad(){
          showArticles(noOfArticles: 100, closure: { url in
            print("Please visit my site \(url)")
          })
            
        }
        func showArticles(noOfArticles: Int, closure: @escaping (String) -> Void) {
          print("advanced development is here!")
            
            // execute the closure 5 seconds after current time
            DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: {
               closure("www.appcodezip.com")
            })
          print("Pls like the AppCodeZip")
        }
    

    When you run the above program, the output will be:

         advanced development is here!

         Pls like the AppCodeZip

         Please visit my site www.appcodezip.com

    Trailing Closures: 

    According to the Apple Documentation, When the closure is being passed as the final argument to a function we can pass it as a trailing closure. 

    A trailing closure is written after the function call’s parentheses, even though it is still an argument to the function.

    When you use the trailing closure syntax, you don’t write the argument label for the closure as part of the function call.

    If the closure argument is the sole argument of the function you can remove the function parentheses. Hence the previous closures can be written as the following and it would still function the same way.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    func someFunctionThatTakesAClosure(closure: () -> Void) {
        // function body goes here
    }
    
    // Here's how you call this function without using a trailing closure:
    
    someFunctionThatTakesAClosure(closure: {
        // closure's body goes here
    })
    
    // Here's how you call this function with a trailing closure instead:
    
    someFunctionThatTakesAClosure() {
        // trailing closure's body goes here
    }
    

    Let’s look at the trailing closure example :

    let digitsList = [1, 2, 3, 4, 5]
    
    let sum = digitsList.reduce(0) { $0 + $1 }
    print(sum)
    // prints 15
    


    Similar solutions you may also like...

    .

      Post a Comment

      0 Comments