How are static variables stored in memory in Swift?
Swift中静态变量是如何存储的?
如果我从未调用func usestaticvar(),会发生什么?这些变量是否已初始化?
如果我调用useStaticVar(),然后再也不访问它们,会发生什么?应收账
1 2 3 4 5 6 7 8 9 10 | struct Something { static var myVariable = 0 static let myConstant = 3 static var myString: String? static func useStaticVar() { myVariable = myConstant myString = String(myVariable) } } |
检查一下:类型属性
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.
必须始终为存储类型属性提供默认值。
您的代码缺少
存储的类型属性在第一次访问时被延迟初始化。
您可以测试并查看如何使用以下代码初始化存储的类型属性:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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() |
输出:
1 2 3 4 | useStaticVar() ZeroGenerator() ThreeGenerator() NilGeneartor() |
编译器可以对常量默认值进行一些优化,但在语义上没有区别。
1 2 | static var myVariable = 0 static let myConstant = 3 |
已初始化。