defer for Resource Cleanup
Close files and release resources reliably.
defer for Resource Cleanup is a free Swift Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.
The Cleanup Problem
Resources like files, locks, or connections must be released. Forgetting to release on some path causes leaks.
func work() {
print("acquire resource")
print("use resource")
print("release resource")
}
work()defer Guarantees Release
Putting the release in a defer guarantees it runs no matter how the function exits.
func work() {
print("acquire resource")
defer { print("release resource") }
print("use resource")
}
work()Simulating a File Handle
Here a simple struct models open/close. The defer ensures close is always called.
struct File {
let name: String
func close() { print("closed", name) }
}
func readFile() {
let f = File(name: "data.txt")
defer { f.close() }
print("reading", f.name)
}
readFile()Lock Acquire/Release
Model a lock: acquire, then defer the release so the critical section is always unlocked.
func critical() {
print("lock acquired")
defer { print("lock released") }
print("critical section work")
}
critical()Cleanup Next to Setup
Keeping the cleanup right after setup makes the pairing obvious and hard to forget.
func session() {
print("connect")
defer { print("disconnect") }
print("send request")
print("receive response")
}
session()Multiple Resources
With several resources, declare each cleanup right after its setup; LIFO order closes them correctly.
func transaction() {
print("open connection")
defer { print("close connection") }
print("begin transaction")
defer { print("commit transaction") }
print("run query")
}
transaction()Counter Reset
A defer can restore state, such as resetting a flag, when a scope ends.
func tracked() {
var active = true
defer { active = false; print("active reset to", active) }
print("active is", active)
}
tracked()Avoiding Duplication
Without defer you would repeat the cleanup on every exit path. defer writes it once.
func validate(_ ok: Bool) {
print("start")
defer { print("cleanup done once") }
if !ok {
print("invalid")
return
}
print("valid")
}
validate(false)Cleanup With Computed Value
A defer can log a final measurement, like how many items were processed.
func batch() {
var processed = 0
defer { print("processed", processed, "items") }
for _ in 1...3 { processed += 1 }
}
batch()Temporary State Restore
Use defer to temporarily change and then restore a setting reliably.
func withVerbose() {
var verbose = false
verbose = true
defer { verbose = false; print("verbose restored:", verbose) }
print("verbose during work:", verbose)
}
withVerbose()Best Practice
Whenever you acquire something that must be released, register the release with defer on the very next line.
func handle() {
print("acquire")
defer { print("release") }
print("process")
}
handle()Quick Check
Test defer for cleanup.
Recap
Register resource release with defer right after acquisition. The cleanup is guaranteed to run on every exit path, keeps teardown next to setup, and avoids duplicating cleanup across return paths.
func work() {
print("acquire")
defer { print("release") }
print("use")
}
work()Learn Swift with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 122
- Lessons
- 409
Frequently Asked Questions
Is the “defer for Resource Cleanup” lesson free?
Yes — any 3 lessons of the Swift Academy learning path, including “defer for Resource Cleanup”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.
What will I learn in “defer for Resource Cleanup”?
Close files and release resources reliably. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
How long does the “defer for Resource Cleanup” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- How defer Works
- Multiple defer Blocks Ordering
- defer for Resource Cleanup
- defer with Errors and Early Returns