什么时候在Swift中使用静态常量和变量? [英] When to use static constant and variable in Swift?
问题描述
有一些关于如何在Swift中为静态常量
和静态变量
编写代码的文章。但是目前尚不清楚何时使用静态常量
和静态变量
而不是使用常量
和变量
。有人可以解释吗?
当您在类(或结构)中定义静态var / let时,该信息将被共享在所有实例(或值)中。
共享信息
class Animal {
静态var nums = 0
init(){
Animal.nums + = 1
}
}
let dog = Animal()
Animal.nums // 1
let cat = Animal()
Animal.nums // 2
在这里您可以看到,我创建了2个 Animal
的单独实例,但是两者共享相同的静态变量变量 nums
。
Singleton
通常为静态常量用于采用Singleton模式。在这种情况下,我们希望分配的类实例不超过1个。
为此,我们将对共享实例的引用保存在常量中,并且隐藏了初始化程序。
class Singleton {
static let sharedInstance = Singleton()
private init(){}
func doSomething(){}
}
现在,当我们需要编写的 Singleton
实例
Singleton.sharedInstance.doSomething()
Singleton.sharedInstance.doSomething()
Singleton.sharedInstance.doSomething()
这种方法的确允许我们始终使用相同的实例,即使在应用程序的不同点也是如此。 / p>
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?
When you define a static var/let into a class (or struct), that information will be shared among all the instances (or values).
Sharing information
class Animal {
static var nums = 0
init() {
Animal.nums += 1
}
}
let dog = Animal()
Animal.nums // 1
let cat = Animal()
Animal.nums // 2
As you can see here, I created 2 separate instances of Animal
but both do share the same static variable nums
.
Singleton
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() { }
}
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屋!