Swift 2.0 introduced a new keyword: defer
What's the correct way of using this keyword, and what should I watch out for?
Since swift uses ARC, memory management is usually taken care of automagically. So defer would only need to be called for memory management for cases where using legacy low level / non arc calls, correct?
Other cases include file access, I imagine. And in these cases defer would be used for closing the "file pointer".
When should use I use defer in the "real-world"(tm) of iOS/OSX development. And when it would be a bad idea to use.
The Swift defer statement is useful for cases where we need something done — no matter what — before exiting the scope. For example, defer can be handy when cleanup actions are performed multiple times, like closing a file or locking a lock, before exiting the scope.
By using defer in Swift you can execute important logic after the return, defer logic, and defer completion callbacks to ensure completion blocks are called.
A defer statement defers the execution of a function until the surrounding function returns. The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
In Golang, the defer keyword is used to delay the execution of a function or a statement until the nearby function returns. In simple words, defer will move the execution of the statement to the very end inside a function.
The proper use of the defer
keyword is within a swift do
, try
, catch
block. Procedures within a defer
statement will always execute prior to exiting the scope of a do
, try
, catch
block. Typically this is used for cleanup, like closing IO.
do {
// will always execute before exiting scope
defer {
// some cleanup operation
}
// Try a operation that throws
let myVar = try someThrowableOperation()
} catch {
// error handling
}
defer
is nice to use if you access C APIs and create CoreFoundation objects, allocate memory, or read and write files with fopen
, getline
. You can then make sure you clean up properly in all cases with dealloc
, free
, fclose
.
let buffSize: Int = 1024
var buf = UnsafeMutablePointer<Int8>.alloc(buffSize)
var file = fopen ("file.txt", "w+")
defer {
buf.dealloc(buffSize)
fclose(file)
}
// read and write to file and and buffer down here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With