Apple introduced a lot of new features during the WWDC 2015. Swift 2.0 will certainly be the most interesting one for developers, considering that it will be released as Open Source by the end of the year.

I had the time to dig into some changes in Swift 2.0, playing with what’s new and what is interesting. I did not find any explanation about the defer statement, so I fired a playground and tried to play with it a little bit.

This statement is actually well known in Go. The go documentation says:

A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions.

So what’s the deal with defer? In a nutshell: the block of code passed as deferred will run when the current function is returned.

Let’s see and example (Playground available):

func deferTest() {
    var string: NSString? = nil
    
    defer {
        if let s = string {
            print(s)
        }
    }
    
    string = "test"
}

deferTest() // This call will print "test"

In this case the defer block is performed after string is assigned. The result is pretty obvious now, the content of the string will be printed in the standard out.

When this is useful? I think Apple introduced this because in system languages is very useful, for example to open a socket and immediately balance it with a closing, deferred, action. Another example is file access, opening and locking a file will require a balanced unlocking and closing call, so we have all the necessary information in few lines of code.

I am happily surprise to see that the Playground is able to handle a deferred block! Very well done!