“静态”的使用是什么?关键字,如果“让”用来快速定义常量/不可变的关键字? [英] What is the use of "static" keyword if "let" keyword used to define constants/immutables in swift?
问题描述
我很快就对使用 static 关键字感到困惑。众所周知,swift引入了 let 关键字来声明不可变对象。就像声明表格视图单元格的ID一样,该ID在生命周期中很可能不会发生变化。现在,在某些struct声明中使用 static 关键字是什么?
I'm little bit confused about using static keyword in swift. As we know swift introduces let keyword to declare immutable objects. Like declaring the id of a table view cell which most likely won't change during its lifetime. Now what is the use of static keyword in some declaration of struct like:
struct classConstants
{
static let test = "test"
static var totalCount = 0
}
而 let 关键字也是如此。在目标C中,我们使用static声明了一些常量,例如
whereas let keyword do the same.In Objective C we used static to declare some constant like
static NSString *cellIdentifier=@"cellId";
此外,让我更好奇的是使用 static 关键字以及让,还有 var 关键字。有人可以解释一下该静态关键字在哪里使用吗?更重要的是,我们真的需要迅速地实现 static 吗?
Besides which makes me more curious is the use of static keyword along with let and also var keyword. Can anybody explain me where to use this static keyword? More importantly do we really need static in swift?
推荐答案
我将为您分解它们:
-
var
:用于创建变量 -
let
:用于创建常量 -
静态
:用于创建类型属性,其中包含let
或var
。这些在类的所有对象之间共享。
var
: used to create a variablelet
: used to create a constantstatic
: used to create type properties with eitherlet
orvar
. These are shared between all objects of a class.
现在,您可以结合使用来获得想要的结果:
Now you can combine to get the desired out come:
-
static let key = API_KEY
:常量类型属性 -
static var cnt = 0
:类型属性为变量 -
let id = 0
:常量(可以只能分配一次,但可以在运行时分配) -
变量价格= 0
:变量
static let key = "API_KEY"
: type property that is constantstatic var cnt = 0
: type property that is a variablelet id = 0
: constant (can be assigned only once, but can be assigned at run time)var price = 0
: variable
因此,将所有内容汇总为var,让定义可变性成为静态,而缺少定义范围。您可能会使用 static var
来跟踪创建的实例数量,而您可能只想使用 var
价格因对象而异。希望这能使事情变得顺利。
So to sum everything up var and let define mutability while static and lack of define scope. You might use static var
to keep track of how many instances you have created, while you might want to use just var
for a price that is different from object to object. Hope this clears things up a bit.
示例代码:
class MyClass{
static let typeProperty = "API_KEY"
static var instancesOfMyClass = 0
var price = 9.99
let id = 5
}
let obj = MyClass()
obj.price // 9.99
obj.id // 5
MyClass.typeProperty // "API_KEY"
MyClass.instancesOfMyClass // 0
这篇关于“静态”的使用是什么?关键字,如果“让”用来快速定义常量/不可变的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!