1

While following a tutorial on using the Keychain feature, I noticed a section of code where I needed to implement a structure as the following:

// Keychain Configuration
struct KeychainConfiguration {
  static let serviceName = "TouchMeIn"
  static let accessGroup: String? = nil
}

I know that a constant property on a value type can't be modified once instantiated so I was curious of the purpose of using static in this sense?


P.S.
This question is not similar to this question because the highest accepted answer (which I would think is the best answer) doesn't provide enough detail or any pros or cons.

informatik01
  • 16,038
  • 10
  • 74
  • 104
Laurence Wingo
  • 3,912
  • 7
  • 33
  • 61
  • 1
    Possible duplicate of [When to use static constant and variable in Swift](https://stackoverflow.com/questions/37701187/when-to-use-static-constant-and-variable-in-swift) – Dávid Pásztor Sep 24 '18 at 15:58
  • 2
    Possible duplicate of [What is the use of “static” keyword if “let” keyword used to define constants/immutables in swift?](https://stackoverflow.com/questions/34574876/what-is-the-use-of-static-keyword-if-let-keyword-used-to-define-constants-im) – Cristik Sep 24 '18 at 15:58
  • The post by @Cristik I think gave more detail as to how the static variable can be used as a type property. – Laurence Wingo Sep 24 '18 at 16:06
  • 1
    You don't have to initialize your struct to access methods or variables that are declared static. You can call them globally via your struct name. – rustyMagnet Sep 24 '18 at 16:13

1 Answers1

2

It has multiple applications, including but not limited by the following:

1) To give a constant separate namespace, if constants have same names.

struct A {
    static let width: Int = 100
}

struct B {
    static let width: Int = 100
}
print(A.width)
print(B.width)

2) Static constants are 'lazy' by design, so if you are about to use lazy-behaved global constant, it might be handy to put it in a structure.

3) To show your coworkers that constant is applicable to specific domain where given structure is used.

4) Organize your configuration in sections:Theme.Layout.itemHeight or Label.Font.avenirNext

fewlinesofcode
  • 3,007
  • 1
  • 13
  • 30