且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift中的隐式惰性成员

更新时间:2022-12-14 20:06:39

static属性定义了一个类型属性",该属性仅被实例化一次.正如您所注意到的,这是懒惰发生的,因为静态行为就像全局变量一样.并且作为 Swift编程语言:属性说:

The static property defines a "type property", one that is instantiated once and only once. As you note, this happens lazily, as statics behave like globals. And as The Swift Programming Language: Properties says:

全局常数和变量总是以与

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:文件和初始化说:

This implicitly lazy behavior is because, as the Swift Blog: Files and Initialization says:

它允许自定义初始化程序,在Swift中启动时间可以干净地缩放,而无需全局初始化程序来减慢它的执行速度,并且执行顺序是完全可预测的.

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.

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

They consciously designed it that way to avoid unnecessarily delaying the startup of the app.

如果要在应用程序中的某个特定点实例化static属性(而不是将其推迟到首次使用它的位置),只需在该点之前引用此static属性,该对象将在以下位置初始化那时.考虑到我们为减少启动应用程序的延迟所做的努力,您通常不会在应用程序的首次启动期间同步地希望这样做,但是您可以在任何需要的地方进行.

If you want to instantiate the static property at some particular point in your app (rather than deferring it to where it's first used), simply reference this static property at that earlier point and the object will be initialized at that time. Given the efforts we put into reducing the latency in starting our apps, you generally wouldn't to want this synchronously during the initial launch of the app, but you can do it wherever you want.