Be Literal!

Swift supports color literals and image literals. A brief explanation on these concepts and some usage examples.

Fernando Martín Ortiz
iOS App Development

--

Literal Colors

We used to write UIColors like this:

let color = UIColor(
red : 100.0/255.0,
green : 100.0/255.0,
blue : 100.0/255.0,
alpha : 1.0
)

Too verbose…

Now, it’s possible to do the same in a much more visual way:

Is as easy as writting ColorLiteral and selecting the first hint.

Choose Color Literal

Then, Xcode will open a handy color picker:

Color picker

The generated color is an UIColor, with all its attributes and methods.

So you can do things like this:

Whenever you want to select another color, just double-click inside any of those rects and the color picker will open again.

Literal Images

Literal images are similar to Literal Colors. You probably already noticed that if you start typing the name of an image asset, Xcode will autocomplete (when autocomplete is working 🤔) with the asset you are looking for.

That result asset is actually an UIImage. It’s a literal UIImage.

If you do the same as with Color Literals, Xcode will open a image picker with which you can select an asset:

This is how the image picker looks like:

The image picker for an image literal

And you can treat the generated images as any other UIImage.

It’s worth noting that the generated image is not optional, which is really cool.

Conclusion

Color and image literals are really great. It reduces verbosity in the code and are much more visual.

I would really like to see this in other classes likeUIFont in the future!

--

--