Using global constants in Swift

If you’re using Swift, you probably know how to create constants:

It’s good practice to use constants instead of variables whenever possible. Since their value can’t be changed afterwards, it’s much safer and compiler can make optimizations if the system knows certain data won’t change.

There’s a lot of good use cases for constants. For example you could use constants for various strings in your app. Or even colors. I’m using Interface Builder, but I still have some colors defined in code:

Note: in case you’re wondering what is UIColor(rgba: ), I’m using this library to create colors easily from hex string.

It would look much nicer if I put those colors into constants:

And then use them like this:

Now there’s big chance I will be using same colors across many view controllers, so it’s a good idea to put them into some file, e.g Constants.swift. We need to do one thing to be able to access them globally – declare them as static:

But after adding few more, it can start to be a clutter. Especially when we start adding other things, like strings. We can tidy it up with structs:

And since structs can be nested, we can make it even more readable:

And now when I want to use them, it’s as simple as that:

That’s it for today :) I hope you found this useful.