Ad space (banner)
๐ŸฆSwift Lessons
Lesson 50 / 68

Cleanup Logic with defer

In this lesson you will learn to write cleanup logic with defer in Swift, so certain work always runs when a function ends. This is for anyone searching for "Swift defer how to use".

Swift has no finally, but defer lets you book work to be run without fail when the function ends. It is the usual choice for closing files or writing a completion log.

The sample code declares defer { print("Ending the calculation") } at the top of divide(), so that message always appears last whether the function returns a value normally or returns nil on failure.

A common stumbling block for beginners is the order in which several defers run. They run in reverse order of declaration - a slightly unusual rule worth remembering.

In real-world development, being able to gather the cleanup in a defer means a function with several exit paths can still clean up safely.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)