What if you could guarantee cleanup code runs perfectly every time, no matter what?
Why Defer statement for cleanup in Swift? - Purpose & Use Cases
Imagine you open a file to read data, then you do many steps like processing and checking errors. You must remember to close the file at the end, no matter what happens. If you forget or an error occurs early, the file stays open and causes problems.
Manually closing resources like files or network connections is tricky. You have to put close commands everywhere, after every possible error or exit point. This is slow, easy to forget, and leads to bugs like memory leaks or locked files.
The defer statement in Swift lets you write cleanup code once, right after opening the resource. Swift guarantees this code runs last, even if errors happen or you return early. This keeps your code clean and safe.
let file = openFile() if error { closeFile(file); return } processFile(file) closeFile(file)
let file = openFile()
defer { closeFile(file) }
if error { return }
processFile(file)It makes your programs safer and easier to read by ensuring cleanup always happens without repeating code.
When downloading a photo from the internet, you open a connection. Using defer, you ensure the connection closes even if the download fails halfway.
Manual cleanup is error-prone and repetitive.
defer runs cleanup code automatically at the end.
This keeps your code simple, safe, and bug-free.