Member-only story
Swift’s defer works in reverse (refed)
So be careful with this one!
I’ve previously written about defer which is used in Swift to clean up resources before exiting a given scope. Which is nice.
Oh, and there is also a video that you might like to watch about exactly this topic: https://youtu.be/Ni-sApIsNM8
However, it seems that defer works in reverse to the order in which it really should (spoiler: if we think of defer as a Stack this isn’t in reverse at all, and makes sense).
Still let us see how defer works with using a rather simple example:
func testDefer() {
defer {print("Do this at the end")}
print("Do some stuff")
}testDefer()
This gives us the following output:
Do some stuffDo this at the end
Which is, of course, deferring the print(“Do this at the end”)
statement to when we are exiting the scope of that function. Rather wonderful.
So what if we have multiple defer statements in a function? Surely it can’t be that tricky, right?
It turns out that it can actually.
func testDefer() {
defer {print ("Do this at the end")}
defer {print ("Do this right at the end")}…