Skip to content

About enumerations in Swift

The last project I have been working on is a set of highly customisable applications, that need to render their user interface according to some configuration downloaded from a remote service. Meh.

But, the thing is, a setup like this leaves a lot of opportunities for Swift to shine. One of those opportunities is implementing color schemes.

The context

All the colours used in an application need to be declared as part of a color scheme, that needs to be downloaded from a remote service. For the shake of this example, we are going to leave the “download it from a remote service” part out of the equation.

A good approach

Well, this is Cocoa, so, the first approach that comes to mind would be declaring an extension on UIColor, and declare the different palette items in it. Something like this:

Which is a perfectly valid approach. But, that is basically a literal translation of what I would do in Objective-C, if I had to figure out a way out of this problem. Which is not bad.

But…

A better approach

The previous approach does not feel very Swift-ish. And, what is worst to me, it does not seem extremely flexible. For example, how would I deal with a requirement such as “yo, bro! can we make the color scheme change at runtime?. Like, you know, light theme during day hours, dark theme during night hours? That’d be sooooo coooooooooool”

Well, let’s try a fresh approach to the problem at hand. What’s a color scheme? To me, it is a set of mutually exclusive values. The active color scheme can be Light, or Dark, not Light and Dark at the same time.

And that, in Swift, is an enumeration. Also, it happens that Swift enumeration can implement methods. So, we could rewrite the previous extension as:

Now, we can set the active scheme as:

And consume it, everywhere in the UI as:

All of that, backed up by the compiler, which will make sure that we do not miss any possible value of the color scheme in its methods.

Final words

Switching to Swift is not only a matter of writing code in a different language, it is also a matter of forgetting about most of the old patterns, and embrace new ways.

And that sounds like a lot of fun to me.

Here is the playground: ColorPalette.playground

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *