What is the correct way to use Swift defer

Swift 2.0 introduced a new keyword: defer

What is the correct way to use this keyword and what should I follow?

Because swift uses ARC, memory management is usually careful about automatic. Thus, deferring is only required for memory management in cases where outdated low-level / non-arc calls are used, right?

Other cases include file access, I suppose. And in these cases, defer will be used to close the "file pointer".

When to use, I use defer in the "real world" (tm) of iOS / OSX development. And when it would be a bad idea to use.

+4
source share
2 answers

Proper use of keywords deferin fast do, try, catchblock. Procedures in the statement deferis always executed before leaving the area do, try, catch. This is usually used for cleaning, such as 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
}
+3
source

deferfun to use, if you have access to the C API and create CoreFoundation objects allocate memory or to read and write files using fopen, getline. Then you can make sure that you clean correctly in all cases with the help of 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
+1
source

Source: https://habr.com/ru/post/1624133/


All Articles