ProgrammingiOS/Swift Developer

What are defer statements in Swift? What are the features of their execution, where is it appropriate to use them, and what pitfalls can one encounter?

Pass interviews with Hintsage AI assistant

Answer.

History of the question:

Defer was introduced in Swift (inspired by analogs in Go, C#) to guarantee resource cleanup even in the event of errors, exiting a function, or returning values from various points in functions.

Problem:

Premature deallocation, forgotten resource cleanups (e.g., closing files, logging, rollback transactions). Sometimes people confuse the order of execution, mistakenly believing that defer executes at declaration time.

Solution:

Defer is a special block that postpones the execution of code until the end of the current scope, usually a function. All defer statements are executed in reverse order of placement (LIFO). This allows centralized management of resource cleanup, memory deallocation, or transaction rollback.

Code example:

func processFile() { let file = File("/tmp/data.txt") file.open() defer { file.close() print("File closed") } // Work with the file print("Reading data…") }

Key features:

  • Always executes on any exit from the scope, even on errors and early returns.
  • Multiple defer statements execute in reverse order.
  • Can be applied in any scope, not just functions.

Trick questions.

Does the code inside defer execute if the application crashes before exiting the function?

No, the defer code only executes on a proper exit from the scope. If the application crashes (for example, due to a fatal error), the defer will not execute.

Can return be used inside defer?

No, it cannot. The defer block does not allow returning values or exiting the scope, only instructions.

Can defer be used to modify variables declared before defer?

Yes, defer captures values from the current stack at execution time. You can modify values declared before defer, and they will be preserved on exiting the scope.

Code example:

func example() -> Int { var result = 0 defer { result = 42 } return result // defer will execute, the result will be 42 }

Common mistakes and anti-patterns

  • Erroneous expectation of defer executing immediately after declaration.
  • Using defer outside of scope where it makes no sense.
  • Leaving heavy operations inside defer.

Real-life example

Negative case

The file is opened, but closed only explicitly at the bottom of the function, leaving the file open on errors or early exit from the function.

Pros:

  • Simplicity of implementation

Cons:

  • File not closed on errors
  • Resource leaks

Positive case

Using defer to close the file immediately after opening. Even if an exception occurs or a return from the function happens, the file will be guaranteed to close.

Pros:

  • Safe, no leaks
  • Clean and predictable code

Cons:

  • Caution is needed with mutable resources inside defer