Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Defer in Swift

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 534
    Comment on it

    Hi,

     

    Swift has introduced a new keyword called 'defer'. Based on its meaning ‘defer’ puts off an action or event to a later time. It runs when the execution is about to leave the code block. You can use ‘defer’ wherever you want in our code block.

    Using defer you can do necessary cleanup regardless of how execution is leaving the block of code.

    func deferExample(){
       let value = 10
        defer {
          print(Defer)
             // Do your coding or cleanup here
        }
         print(Returning")
         return
    }

    If you call the function then “Returning” text will be printed before “Defer” text. so it's clear that defer is executing the block at last or when execution is about to leave the code block.

    More than one defer can also be used in a method and their execution will in reverse chronological order.  If you’ve multiple defer statements in your code block(as shown here) 

    func multiDeferExample(){
    
        let value = 10
        defer {
          print(Defer 1)
             // Do your coding or cleanup here
        }
            defer {
    
          print(Defer 2)
             // Do your coding or cleanup here
        }
        print(Returning")
        return
    }

     

    In above case firstly the “Defer 2” will work and then “Defer 1” will be executed. so by using defer you can make necessary changes or cleanup right before leaving the code block.

     

    Note- Defer doesn’t allow break or return statement in their code block.

     

    Thank You

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: