The defer
statement comes as part of the new error handling model in Swift 2.0. Its primary purpose is to help with cleanup of resources in the face of possible early exits due to errors being thrown.
But the use of defer
is not limited to error handling. Just recently, I had to write some code to render an UIImage in a function similar to this:
func renderImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
// Do some drawing
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
I was annoyed about the necessity of the temporary image
variable when it occured to me that defer
could be used to clean up that code:
func renderImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
defer { UIGraphicsEndImageContext() }
// Do some drawing
return UIGraphicsGetImageFromCurrentImageContext()
}
There is no need for a temporary variable anymore and the whole code looks a little bit cleaner to me. Its a little change, but one that makes me happy.
Markus is a technical mastermind and one of the founders of Innovaptor. He studied Computer Engineering at Vienna University of Technology and contributes a valuable diversification to Innovaptor's qualifications. Markus is eager to find innovative solutions to complex problems in order to provide products that are tailored directly to the customers' needs