What's the best practice to use Global variable vs static local variable

We have a discussion about when to use a global variable or local variable but didn't come to a specific conclusion. Is there any guidance or best practice to choose when to use a global or local static variable?

Such as

let sharedTest = Test()

class Test {
    static let shared = Test()

@Joe_Groff @John_McCall Hey sorry to @ you, maybe it's too simple for you to answer, but I did search on the network and checked the docs of swift and didn't find any useful information.

They are identical from an implementation standpoint. It's really up to your judgment whether a global property should be scoped to the module or is related to a specific type.


Sometime you have no choice:

struct Foo<T> {
    static var x = 1    // error: static stored properties not supported in generic types
    // this is okay but it's evaluated on every access
    static var x: Int { 1 }
1 Like

That's a good example!

To be clear, if that were supported, it would have different semantics from declaring it at the top level, because you’d have a different variable for each set of generic arguments.


I for one would very much like this feature.

I would use it when writing a mathematical function that’s generic over one of the numeric protocols, and which involves caching previously-computed values.