Hidden feature: enum
You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿
I’m certain you’ve already used an enum
in your code.
But did you know that enums have a hidden feature?
Let me explain!
Imagine that you’ve defined some constants in your project.
Right now these constants are part of the global namespace.
But you know that it’s usually considered a bad practice to pollute the global namespace.
So it would be better if we stored these constants inside a scope of their own.
A solution that easily comes to mind would be to define a struct
and turn the constants into static
members of that struct
.
This approach indeed does the job of taking the constants out of the global namespace, but also introduces a small drawback: since we’ve defined a struct
, it becomes possible to create values using that struct
.
But doing so doesn’t make any sense and will only be a source of confusion, so we would probably want to disallow it by making the init
of the struct
explicitly private
.
But did you know that there’s a better approach to solve this problem?
As you can imagine, this is when an enum
comes into play!
We’re going to remove our struct
and its private
init
, and replace it with an enum
.
And this time we’ve created the perfect wrapper for our constants: not only are they are no longer stored directly in the global namespace, but because our enum
doesn’t declare any case
it is also automatically impossible to create a value of type Constant
!
As it turns out, this trick of using an enum
as a namespace is far from being a fringe practice: the Swift Standard Library itself actually makes use of it!
That’s all for this article, I hope you’ve enjoyed discovering this new feature!
Here’s the code if you want to experiment with it:
import Foundation
enum Constant {
static let baseUrl = URL(string: "https://myapi.com")
static let apiPath = "/api/v2/"
static let apiKey = "fskf8h99Fs7HV1jHNJF19g0268"
}