何时在Swift中使用静态常量和变量 [英] When to use static constant and variable in Swift
问题描述
如何在Swift中编写静态常量
和静态变量
的代码。但目前尚不清楚何时使用静态常量
和静态变量
而不是常量
和变量
。有人可以解释一下吗?
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
.
通常是静态的常量用于采用Singleton模式。在这种情况下,我们希望分配不超过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()
这种方法确实允许我们始终使用相同的实例,即使在app的不同点也是如此。
This approach does allow us to use always the same instance, even in different points of the app.
这篇关于何时在Swift中使用静态常量和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!