什么时候在 Swift 中使用静态常量和变量? [英] When to use static constant and variable in Swift?

查看:29
本文介绍了什么时候在 Swift 中使用静态常量和变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些帖子介绍了如何在 Swift 中为 static constantstatic variable 编写代码.但不清楚何时使用static constantstatic variable 而不是constantvariable.谁能解释一下?

There are some posts for how to write code for static constant and static variable in Swift. But it is not clear when to use static constant and static variable rather than constant and variable. Can someone explain?

推荐答案

当您将静态 var/let 定义到类(或结构)中时,该信息将在所有实例(或值)之间共享.

When you define a static var/let into a class (or struct), that information will be shared among all the instances (or values).

class Animal {
    static var nums = 0

    init() {
        Animal.nums += 1
    }
}

let dog = Animal()
Animal.nums // 1
let cat = Animal()
Animal.nums // 2

正如您在此处看到的,我创建了 2 个单独的 Animal 实例,但它们共享相同的静态变量 nums.

As you can see here, I created 2 separate instances of Animal but both do share the same static variable nums.

通常使用静态常量来采用单例模式.在这种情况下,我们希望分配的类实例不超过 1 个.为此,我们将共享实例的引用保存在一个常量中,并隐藏了初始化程序.

Often a static constant is used to adopt the Singleton pattern. In this case we want no more than 1 instance of a class to be allocated. To do that we save the reference to the shared instance inside a constant and we do hide the initializer.

class Singleton {
    static let sharedInstance = Singleton()

    private init() { }

    func doSomething() { }
}

现在当我们需要 Singleton 实例时,我们编写

Now when we need the Singleton instance we write

Singleton.sharedInstance.doSomething()
Singleton.sharedInstance.doSomething()
Singleton.sharedInstance.doSomething()

这种方法确实允许我们始终使用相同的实例,即使在应用程序的不同点也是如此.

This approach does allow us to use always the same instance, even in different points of the app.

这篇关于什么时候在 Swift 中使用静态常量和变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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