Search code examples
swiftdeferred

What's the proper way of using Swift's defer


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.


Solution

  • 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
    }