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!
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. Tricks like identifiers containing alternate semicolons, parens or curlies would probably stand out using something as simple as syntax coloring. The sneakier lookalikes can be caught using automation like SwiftLint or Danger. 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!