Fun with Unicode in Swift
I recently saw an article suggesting that Go may get unicode identifiers in 2.0 (original proposal/discussion on GitHub). Now, I don’t use golang, but another language I do know and love already supports this. The news and discussion reminded me of some things I’ve read and thought about with regards to Swift, so I’m putting it all down here.
Unicode in Swift
Swift can include Unicode in identifier names, like variables, functions or enum/protocol/value/class definitions (but importantly, not in operators). This gives developers the ability to write code that is internationalized, appears more mathematical or just looks like Glitchr_’s Twitter feed. In the spirit of the exquisite how to write unmaintainable code, let’s look at a few fun things that could be done to write unmaintainable Swift code!
I use the awesome FiraCode font face in Xcode (and everything else!), hence in all these screenshots. Unicode characters will render differently for different fonts. For many of these tricks, it’s obvious where the differences lie, but that may not be as true for all typefaces.
Unicode has lots of alternative codepoints for the same character. Put them to work to help store more data, seemingly without the need to create more variables!
You can replace combinations of letters with ligatured versions…
…or hide operator-like glyphs to fake expressions.
When in Rome…
…it’s all Greek to me!
Full-width characters can fake a function…
…and you can always use the Socratic method!
The original inspiration for this post was a zero width space in some text I copied from a JIRA ticket right to code. It took me a bit to figure out what’d happened, and with any luck, equally so for each your colleagues! That’s what we call network effect.
They’re much slower to type, and many are nearly indistiguishable from one another, but emoji use in Swift sure is fun 🎉!
mutating keyword just doesn’t drive the point home enough. You need to make those functions strike fear into the hearts of those who would invoke such dangerous spells!
Dark Ages of Code? 🌚
This is all fun and games, but what if we were to use Unicode in earnest and then things change, like Apple changing a deadly revolver to a harmless and fun watergun? Given enough time, could entire code sectors and execution paths become unreadable, their intent lost along with the sensibilities of a previous programmer, design team, society, or civilization?
I don’t think we’re at a point where we use enough Unicode in code to worry about any significant meaning to be lost in translation or redesigns. Nor do I think most of these tricks would get by a code review or go unnoticed using something as simple as syntax coloring. The most I’ve been harmed thus far is a 5 minute head-scratcher… I’m not too worried about the future 😎
Toy with some head-scratchers of your own with the Xcode Playground containing these Swift Unicode examples, and if you figure out something interesting, submit a PR!