dannliu
(Danny Liu)
1
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()
}
dannliu
(Danny Liu)
2
@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.
Joe_Groff
(Joe Groff)
3
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.
6 Likes
young
(rtSwift)
4
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
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.
6 Likes
Nevin
7
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.
6 Likes