Software Dev

Decompiling Swift’s “defer” operator

The Swift “defer” operator my not work exactly like you expect. It’s not exactly the last code executed before the function returns. Well, it kind of is. But also not so much. 🤦🏻‍♂️ As this article says, “defer” basically happens at the “ret” in “return”. 🤯

It takes a while to process what’s going on here, so take your time…

It’s also fascinating to see how what some very simple Swift code looks like when decompiled. Temporary registers. Global var access. Code injection in all the wrong places. 🤯 I have newfound respect for compiler writers.

And thanks to Sergey Smagleev on Medium for a great deep dive into “defer”.

Whoa, a simple three-liner has turned into this abomination that spans 34 lines of code.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.