Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way of using Swift's defer [closed]

Tags:

swift

deferred

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.

like image 459
raf Avatar asked Jan 13 '16 14:01

raf


People also ask

How does defer work in Swift?

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.

Is defer called after return Swift?

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.

What is defer statement?

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.

What is defer in Golang?

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.


2 Answers

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
}
like image 159
wmcbain Avatar answered Nov 09 '22 12:11

wmcbain


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
like image 20
orkoden Avatar answered Nov 09 '22 12:11

orkoden