Swift Defer Statement explained

When you want to ensure that a code block is executed just before control exits the scope, Swift Defer Statement comes to your rescue. Sometimes a function is required to have multiple conditional exit point and covering those exit points without swift defer statement can lead to code duplication or it might just not be possible to cover those exit point.

By Exit point, I mean any exit condition where the control moves out of the scope in which Defer is defined, it might return, break or throw an error. The code which is written under defer block will be executed last just before the control exits the scope.

//Example without a return statement
func testDefer(){
    //Function without return
    defer{
        print("print under defer")
    }
    print("last statement")
}
//OUTPUT
//last statement
//print under defer
//Example with a return statement
func testDefer1(){
    //Function with return
    defer{
        print("print under defer")
    }
    print("last statement")
    return
}
//OUTPUT
//last statement
//print under defer

As you can see in the above examples code under defer block is executed last just before the control exit. Swift defer statement can come in handy with a function having multiple guard statement either returning breaking or throwing. Defer can be used for cleanup like emptying a buffer or closing open file or terminating a connection just before exit irrespective of exit condition.

Multiple Swift Defer Statement

You can use multiple defer statement in swift. If multiple swift deffer statements are used within the function then they are called in LIFO that is the last defined Defer is called first. The example below will clear things up.

func multipleDefer(){
    defer{
        print("defer 1")
    }
    defer{
        print("defer 2")
    }
    defer{
        print("defer 3")
    }
//creating an error by typecasting space to Int
    guard let a = "" as? Int else{
        print("In Guard")
        return
    }
return
}

multipleDefer()
//Output
In Guard
defer 3
defer 2
defer 1


You can see the defer 3 is called first then defer 2 and defer 1 is called last.

You should define defer block preferably on the top of your scope which you wish to cover.

A pat on the back !!