7

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.

raf
  • 2,569
  • 20
  • 19
  • Maybe this will help you? https://www.hackingwithswift.com/new-syntax-swift-2-defer – NBoymanns Jan 13 '16 at 14:55
  • Possible duplicate of [What's the equivalent of finally in Swift](http://stackoverflow.com/questions/30974104/whats-the-equivalent-of-finally-in-swift) – Eric Aya Jan 13 '16 at 14:58
  • thanks. But well, that's more theoretical. I mean from a practical standpoint. What are/should be the best practice for when to use and not to use defer. – raf Jan 13 '16 at 14:58
  • @EricD. I saw that question/answer. I'm wondering about best practices. Let me update the question. thanks. – raf Jan 13 '16 at 14:59
  • 1
    Be careful, because asking for best practices will lead your question to be closed as "opinion based". You should avoid asking for best practices on SO. – Eric Aya Jan 13 '16 at 14:59
  • 1
    "Theoretical"? I see answers over there that are good practical examples. – Eric Aya Jan 13 '16 at 15:01
  • But the only meaningful example there is to use defer for closing a file access. What about other cases where it would make sense to use / not make sense to use?. Thanks @EricD. – raf Jan 13 '16 at 15:31
  • I understand, you want more different examples. I still think it's a duplicate but I've removed my close vote anyway as you think it's not. But as I said, you should remove the "best practices" part from your question and only ask factual questions, otherwise your question will be closed as "opinion based". :) – Eric Aya Jan 13 '16 at 15:33
  • I/O stream and ensuring it is closed at the end of the scope is an example – Oliver Atkinson Jan 13 '16 at 17:25

2 Answers2

10

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
}
wmcbain
  • 1,099
  • 9
  • 16
  • 1
    This is good data. So `defer` should only be used within these specific scopes? This is useful. My understanding was that it could be used anywhere in a function. And my question was where in that function does it make sense to `defer` and for what. And also, when/how not to use it. – raf Jan 13 '16 at 15:38
4

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
orkoden
  • 18,946
  • 4
  • 59
  • 50