Clicky

iOS Dev Nugget 209 Swift Defer

.

Need to run a code review on your codebase? Hire me

Swift 2.0 introduced the defer statement that let us run code just before a function returns.

This is especially useful if you need to clean up resources at multiple points within the same function. E.g.

func writeOutput() {
    var stream: NSOutputStream //initialize it. Possibly a subclass
    if (someCondition) {
        doSomething()
        stream.close()
        return
    } else {
        doSomethingElse()
    }
    stream.close()
}

The example above is contrived, and the code can be improved with some refactoring. But in the function, you can see that clean up code (stream.close()) has to be run at two places. This breaks the DRY principle, and is easy to miss when you modify the code. With the defer statement you can rewrite it:

func writeOutput() {
    var stream: NSOutputStream //initialize it. Possibly a subclass
    defer {
        stream.close()
    }
    if (someCondition) {
        doSomething()
        return
    } else {
        doSomethingElse()
    }
}

The code in the defer block runs right before the function returns. So clean up code only appears once and is close to the initialization code, making it easier to reason. You can write multiple defer blocks in a function and they will be called in reverse order if you initialize multiple resources.

So use defer. Cleaner, fewer errors.


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues