April 2026
Intermediate
683 pages
25h 29m
English
In Swift, defer is a powerful keyword targeting cleanup code. With defer, you can ensure that a cleanup code block runs no matter how a function exists—even if it throws an error. Which is, obviously, the topic at hand.
What do we mean by cleanup code? Table 12.2 features some examples to answer that question.
|
Function’s Operation |
Cleanup Code |
|---|---|
|
File handling |
Closing the file |
|
Database transactions |
Closing the database connection |
|
Network session |
Closing the socket |
|
Temporary files |
Deletion of the files |
|
Locking resources |
Unlocking resources |
Table 12.2 Some Cleanup Code Examples
Focusing on the network session example, imagine that your function opens a network connection to ...
Read now
Unlock full access