Search code examples
naming-conventionsconstantsswiftglobal

Swift: Global constant naming convention?


In Swift, it seems that global constants should be camelCase.

For example:

let maximumNumberOfLoginAttempts = 10

Is that correct?

I'm used to all caps, e.g., MAXIMUM_NUMBER_OF_LOGIN_ATTEMPTS, from C, but I want to acquiesce to Swift conventions.


Solution

  • 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)