“静态"有什么用?关键字 if “let"用于在 swift 中定义常量/不可变的关键字? [英] What is the use of "static" keyword if "let" keyword used to define constants/immutables in swift?

查看:22
本文介绍了“静态"有什么用?关键字 if “let"用于在 swift 中定义常量/不可变的关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在 swift 中使用 static 关键字有点困惑.正如我们所知,swift 引入了 let 关键字来声明不可变对象.就像声明一个表格视图单元格的 id 一样,它在其生命周期内很可能不会改变.现在在某些结构声明中使用 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 关键字做同样的事情.在 Objective C 中,我们使用 static 来声明一些常量,如

whereas let keyword do the same.In Objective C we used static to declare some constant like

static NSString *cellIdentifier=@"cellId";

除此之外,让我更加好奇的是将 static 关键字与 letvar 关键字一起使用.谁能解释我在哪里使用这个静态关键字?更重要的是,我们真的需要 swift 中的 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 : 用于创建一个常量
  • static :用于创建 输入属性.这些在一个类的所有对象之间共享.
  • var : used to create a variable
  • let : used to create a constant
  • static : used to create type properties with either let or var. 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 : 常量(只能赋值一次,但可以在运行时赋值)
  • var price = 0 : 变量
  • static let key = "API_KEY" : type property that is constant
  • static var cnt = 0 : type property that is a variable
  • let 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 varfor 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

这篇关于“静态"有什么用?关键字 if “let"用于在 swift 中定义常量/不可变的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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