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

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

概述正如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 us 正如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. (在任何一个例子中都没有理由使用课程,至少在你提出问题的方式上.)

总结

以上是内存溢出为你收集整理的斯威夫特:什么时候应该使用“var”而不是“let”?全部内容,希望文章能够帮你解决斯威夫特:什么时候应该使用“var”而不是“let”?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1046735.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存