Hi all,
In Swift, I often see static helper functions grouped in an enum without any cases, like this:
enum StringUtils {
static func camelCaseToSnakeCase(_ input: String) -> String {
// implementation
}
}
Since this enum has no cases, it cannot be instantiated – which is exactly the point. It’s meant to group related functionality without any stored state, and without the need for instantiation.
This pattern avoids writing a struct with a private init() and makes the intent clearer: "This is just a static utility, not an object."
You’ll often see this used for things like:
AnalyticsEvents.track(_:)
My question: Is this use of a case-less enum considered good practice in Swift when building static-only helpers?
Or is there a better alternative for expressing intent and preventing instantiation?
I’d appreciate any insight – especially if there’s official guidance or references from the Swift core team.
Thanks!
especially if there’s official guidance or references from the Swift core team.
The Swift Core Team doesn’t hang out here on DevForums. Rather, pop on over to Swift Forums.
Or is there a better alternative for expressing intent and preventing instantiation?
Not that I’ve seen.
You can prevent external instantiation of a struct by adding a private initialiser:
struct MyStruct {
private init() { }
static func helper() { }
}
However, that has some drawbacks:
- It’s extra code.
- It doesn’t prevent internal instantiation.
Honestly, I think the caseless enum is the best option here, and it doesn’t surprise me that the community seems to have standardised on it.
Having said that, I get the feeling that I overuse this technique personally. It’s tempting to use it when a better option would be to namespace via a module. To take your first example, if StringUtils
were a module and camelCaseToSnakeCase(_:)
were a free function within that module, folks could call camelCaseToSnakeCase(_:)
directly or, if it makes them feel better, use StringUtils.camelCaseToSnakeCase(_:)
.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"