Swift 中的隐式惰性静态成员 [英] Implicitly lazy static members in Swift

查看:34
本文介绍了Swift 中的隐式惰性静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just noticed that static members of Swift structs are implicitly lazy.

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

For instance, this will only call the init once:

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

var z = Foo.bar
z = Foo.bar

这背后的原理是什么?

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

What if I want the opposite behaviour?

推荐答案

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:

全局常量和变量总是以类似于延迟存储属性.与惰性存储属性不同,全局常量和变量不需要用 lazy 修饰符标记.

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

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.

请注意,与 lazy 实例属性不同,全局变量和 static 变量的实例化是线程安全的.

Note that unlike lazy instance properties, the instantiating of globals and static variables is thread-safe.

这篇关于Swift 中的隐式惰性静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆