Swift: The 😎 Case of An Enum With No Cases

Earlier today, I wrote about all the unconventional ways I use extensions in Swift to make my code more readable. This somehow triggered an interesting discussion on Twitter around Swift naming conventions. I won’t go into detail on that here – you can read the full discussion yourself if you’d like. But I did learn something super cool:

Whoa! Apparently 1. you can have an enum with no cases! And 2. an enum with no cases is perfect for namespaced constants!

My favorite example of namespaced constants comes from @jesse_squires:

But the problem is that another developer might not know much about ColorPalette and easily instantiate it like this:

Which can get confusing… 🤔

Making ColorPalette an enum with no cases instead of a struct solves this problem!

An enum with no cases cannot be initialized, so now when you try to instantiate the enum version of ColorPallete, you get this error!

Enum no cases error swift

Love this simple trick! Thanks @jl_hfl!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.