How are static variables in Swift stored?
What happens if I never call the func useStaticVar() ? Are these variables initialised or not?
What happens if I do call useStaticVar() and then never access them again? Ar
struct Something {
static var myVariable = 0
static let myConstant = 3
static var myString: String?
static func useStaticVar() {
myVariable = myConstant
myString = String(myVariable)
}
}
data segment stores Swift static variables, constants and type metadata.
The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).
Static methods are stored in Metaspace space of native heap as they are associated to the class in which they reside not to the objects of that class. But their local variables and the passed arguments are stored in the stack.
Static methods as well as static variables are stored in the heap memory, since they are part of the reflection data (class related data, not instance related).
Check this: Type Properties
NOTE
Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.
Stored type properties are lazily initialized on their first access. They are guaranteed to be initialized only once, even when accessed by multiple threads simultaneously, and they do not need to be marked with the lazy modifier.
you must always give stored type properties a default value.
Your code lacks a default value for myString
, in such cases, Swift give it a default nil
.
Stored type properties are lazily initialized on their first access.
You can test and see how stored type properties are initilized with some code like this:
func ZeroGenerator() -> Int {
print(#function)
return 0
}
func ThreeGenerator() -> Int {
print(#function)
return 3
}
func NilGeneartor() -> String? {
print(#function)
return nil
}
struct Something {
static var myVariable = ZeroGenerator()
static let myConstant = ThreeGenerator()
static var myString: String? = NilGeneartor()
static func useStaticVar() {
print(#function)
myVariable = myConstant
myString = String(myVariable)
}
}
Something.useStaticVar()
Output:
useStaticVar()
ZeroGenerator()
ThreeGenerator()
NilGeneartor()
Compiler may make some optimizations for constant default values, but semantically no difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With