Since graduating from the Flatiron School, I’ve been working on side projects to familiarize myself with all of the concepts I learned over the last 4 months. Throughout the duration of the program, I heavily relied on Stack Overflow as a resource to find simple solutions to problems or bugs I faced. Although I deem it appropriate to use these solutions, it’s essential that I understand these concepts. One concept in particular that I realized I’m not familiar with is the defer statement.
Apple’s “Swift Programming Language (Swift 2.2)” defines defer statements as:
“A defer statement is used for executing code just before transferring program control outside of the scope that the defer statement appears in.”
Essentially what this is saying is that a defer statement, living up to the definition of the word itself, is putting off or postponing a function call onto a list. This list of saved function calls get executed after other surrounding function calls. The purpose of this is to ensure that the function will run prior to the current scope ending. A great example showcasing defer can be in simple print statements below:
As you can see here, the defer statement is within the numbers method and it is essentially saying to hold off on printing the number 3. If you run this program, you will get the following order: 1,2,4,3,5. The number 3 is not last because it print at the end of it’s current scope, which is the numbers method.
Developers can defer multiple blocks of code but note that when executing, the statements will be in reverse order where the most recent deferred statement will run first.