Some operators improve code clarity

Conor Brady
2 min readApr 26, 2017

--

This is an infix, Swift operator; improving code expressivity and clarity. It gives a syntactic abstraction of something constantly done with mutable frameworks such as UIKit. We use it heavily on the HubSpot iOS team, becoming an indispensable tool in writing clear, maintainable code such as:

Here’s the implementation:

Below, I’ll list examples of its use; with hopeful evidence of of its merit.

What?

We initialise Foo, but it’s not really initialised since we immediately want to assign bar. For some reason, Foo doesn’t accept bar in the constructor, so we end up with a create-assign pattern.

With <== , we arrive at a better expression of our intent and we avoid assigning invalid states of foo.

But, what about the real world?

A pretty typical UIKit interaction:

After we apply <==:

This creates a single assignment and clear initialisation block. The blocks encourage the code to be grouped logically, with a strong syntactic contract.

If we mutated these objects outside their blocks, it would stand out. So we get reassurances that we have the full picture of any objects configuration and mutations at a glance. Even the layer configuration for the button’s drop shadow falls into place nicely.

But wait, theres more

Since we have customisable single assignment, we can apply it at the class level:

This constrains the creation to constant, class level information; factoring out anything that depends on parameters to the init call.

It also removes order dependency, so any order dependant mutations can be performed in the initialiser itself, reducing the noise surrounding interdependent, order specific instructions.

It all feels much more declarative. Like UI code should feel.

I need more convincing…

At line 2, we don’t need v1 and v2 but we’re just using them as temporary variables so we can assign them titles, before passing them as arguments to the UITabBarController constructor. This is mostly how this pattern plays out in the wild.

Line 11 feels a lot better. We avoid polluting the symbol table with variables that are unnecessary; with the scope of use of the view controllers clearly indicated by the context of their creation and use.

This is more readable, as everything appears in context to it creation, modification and purpose. Rather than splitting that across three lines.

I’m sold

Try it out, it’s only 7 lines. It’s made our code much more easy to read and maintain. You’ll be glad of it.

Next thing, you can start making style-extensions.

Any or all of this sound interesting? Join the HubSpot iOS team.

--

--