Swift 中的隐式惰性静态成员

Implicitly lazy static members in Swift

我刚刚注意到 Swift structsstatic 成员隐式 lazy

例如,这只会调用 init 一次:

class Baz {
    init(){
        print("initializing a Baz")
    }
}
struct Foo {
    static let bar = Baz()
}

var z = Foo.bar
z = Foo.bar

这背后的原理是什么?

如果我想要相反的行为怎么办?

static 属性 定义了一个“类型属性”,一个只被实例化一次的类型。正如您所注意到的,这是懒惰地发生的,因为静态行为就像全局变量。正如 The Swift Programming Language: Properties 所说:

Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties. Unlike lazy stored properties, global constants and variables do not need to be marked with the lazy modifier.

这种隐含的懒惰行为是因为,正如 Swift Blog: Files and Initialization 所说:

it allows custom initializers, startup time in Swift scales cleanly with no global initializers to slow it down, and the order of execution is completely predictable.

他们有意识地以这种方式设计,以避免不必要地延迟应用程序的启动。

如果您想在应用程序的某个特定点实例化 static 属性(而不是将其推迟到首次使用的位置),只需引用此 static 属性 在那个较早的点,对象将在那个时候被初始化。考虑到我们为减少启动应用程序的延迟所做的努力,您通常不希望在应用程序的初始启动期间同步执行此操作,但您可以在任何需要的地方执行此操作。


请注意,与 lazy 实例属性不同,全局变量和 static 变量的实例化是 thread-safe。