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.