Swift: Global constant naming convention?
I've been debating using camel case with a leading capital for class-level constants. For example:
static let MaximumNumberOfLoginAttempts = 10
It's still camel-case (as Apple appears to recommend), but the capitalized leading character makes it clear that the value is immutable.
Apple advocates the camelCase. That said, many use _camelCase just to differentiate it especially if you are likely to have the same name at a lower scope.
Swift 3 API guidelines state that "Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase."
https://swift.org/documentation/api-design-guidelines/
Ideally your global constants will be located within an enum
, extension
, or struct
of some sort, which would be UpperCamelCase, and all properties in that space would be lowerCamelCase.
struct LoginConstants {
static let maxAttempts = 10
}
And accessed like so,
if attempts > LoginConstants.maxAttempts { ...}
(credit to Ryan Maloney's answer for calling out the benefits of enum
)
To improve on bmjohns answer, it's better to use an enum
instead of a struct
to act as a namespace for your constants. An enum
with no cases can't be instantiated, whereas a struct
can. If it is a struct
, then instantiating it (via LoginConstants()
) is allowed, but that has no meaning and doesn't make sense to do.
The convention is to use enumerations for namespacing, as such:
enum LoginConstants {
static let maxAttempts = 10
}
This ensures that the only valid usage of LoginConstants
is for accessing its static members.