加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

斯威夫特:什么时候应该使用“var”而不是“let”?

发布时间:2020-12-14 05:42:58 所属栏目:百科 来源:网络整理
导读:正如Apple文档所说: Use let to make a constant and var to make a variable. The value of a constant doesn’t need to be known at compile time,but you must assign it a value exactly once. This means you can use constants to name a value that
正如Apple文档所说:

Use let to make a constant and var to make a variable. The value of a constant doesn’t need to be known at compile time,but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.

让我们考虑一下课程:

class A {
    var a = [String]()
}

由于数组a是可变的,因此它是通过var定义的.但是如果我们考虑B类,A的实例是属性呢?

class B {
    let b = A()
}

即使b是可变的,让关键字也可以,因为引用不会被改变.另一方面,var也可以,因为b的内容可以改变.我应该在这个例子中选择什么 – let或var?

尽可能使用let.必要时使用var.使事情不可变会使很多错误成为不可能,所以它应该是你的默认选择.尽可能在init中设置所有值,永远不要更改它们.同样,你应该尽可能使用struct,并在必要时进行分类(尽管根据我的经验,这比使用let更难实现).

所以在你的例子中,如果你在初始化期间不能设置A.a,那么是的,它应该是var.但是在你的例子中没有必要为B.b.使用var. (在任何一个例子中都没有理由使用课程,至少在你提出问题的方式上.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读