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
.
.