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:
@gonzalo__nunez @natashatherobot @swizzlr @cocoaphony If they are very global I use lowerCameCase static constants on enum with no cases.
— Joseph Lord (@jl_hfl) March 29, 2016
@cocoaphony @gonzalo__nunez @natashatherobot @swizzlr You can’t instantiate it (no cases).
— Joseph Lord (@jl_hfl) March 29, 2016
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Taken from http://www.jessesquires.com/swift-namespaced-constants/ struct ColorPalette { static let Red = UIColor(red: 1.0, green: 0.1491, blue: 0.0, alpha: 1.0) static let Green = UIColor(red: 0.0, green: 0.5628, blue: 0.3188, alpha: 1.0) static let Blue = UIColor(red: 0.0, green: 0.3285, blue: 0.5749, alpha: 1.0) struct Gray { static let Light = UIColor(white: 0.8374, alpha: 1.0) static let Medium = UIColor(white: 0.4756, alpha: 1.0) static let Dark = UIColor(white: 0.2605, alpha: 1.0) } } // Usage let red = ColorPalette.Red let darkGray = ColorPalette.Gray.Dark |
But the problem is that another developer might not know much about ColorPalette and easily instantiate it like this:
1 |
let myColorPallete = ColorPalette() |
Which can get confusing… 🤔
Making ColorPalette an enum with no cases instead of a struct solves this problem!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// ColorPalette is now an enum with no cases! enum ColorPalette { static let Red = UIColor(red: 1.0, green: 0.1491, blue: 0.0, alpha: 1.0) static let Green = UIColor(red: 0.0, green: 0.5628, blue: 0.3188, alpha: 1.0) static let Blue = UIColor(red: 0.0, green: 0.3285, blue: 0.5749, alpha: 1.0) // Gray is now an enum with no cases! enum Gray { static let Light = UIColor(white: 0.8374, alpha: 1.0) static let Medium = UIColor(white: 0.4756, alpha: 1.0) static let Dark = UIColor(white: 0.2605, alpha: 1.0) } } // This still works as expected! let red = ColorPalette.Red let darkGray = ColorPalette.Gray.Dark |
An enum with no cases cannot be initialized, so now when you try to instantiate the enum version of ColorPallete, you get this error!
Love this simple trick! Thanks @jl_hfl!