“ let”到底有多精确? Swift中的关键字工作? [英] How exactly does the "let" keyword work in Swift?

查看:79
本文介绍了“ let”到底有多精确? Swift中的关键字工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了指南中的以下简单说明:

I've read this simple explanation in the guide:


在编译时不需要知道常量的值时间,但是您必须为它分配一次值。

The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once.

但是我想要的是更多细节。如果该常量引用了一个对象,是否仍可以修改其属性?如果它引用一个集合,是否可以在其中添加或删除元素?我来自C#背景;它与 readonly 的工作方式类似(除了能够在方法主体中使用它),如果不是,则有什么不同?

But I want a little more detail than this. If the constant references an object, can I still modify its properties? If it references a collection, can I add or remove elements from it? I come from a C# background; is it similar to how readonly works (apart from being able to use it in method bodies), and if it's not, how is it different?

推荐答案

let 有点像 const C中的指针。如果使用 let 引用对象,则可以更改该对象的属性或调用该对象的方法,但不能将其他对象分配给该标识符。

let is a little bit like a const pointer in C. If you reference an object with a let, you can change the object's properties or call methods on it, but you cannot assign a different object to that identifier.

let 对集合和非对象类型也有影响。如果引用带有 let 结构,则不能更改其属性或调用其任何变异函数方法。

let also has implications for collections and non-object types. If you reference a struct with a let, you cannot change its properties or call any of its mutating func methods.

使用 let / var带有集合的就像可变/不可变的Foundation集合一样:如果将数组分配给 let ,则不能更改其内容。如果您使用 let 引用字典,则无法添加/删除键/值对或为键指定新值-这是真正不变的。如果要分配数组,字典中的下标,追加或以其他方式对其进行突变,则必须使用 var 对其进行声明。

Using let/var with collections works much like mutable/immutable Foundation collections: If you assign an array to a let, you can't change its contents. If you reference a dictionary with let, you can't add/remove key/value pairs or assign a new value for a key — it's truly immutable. If you want to assign to subscripts in, append to, or otherwise mutate an array or dictionary, you must declare it with var.

(在Xcode 6 beta 3之前,Swift数组具有值和引用语义的怪异组合,并且在分配给 let 时是部分可变的-这就是现在消失了。)

(Prior to Xcode 6 beta 3, Swift arrays had a weird mix of value and reference semantics, and were partially mutable when assigned to a let -- that's gone now.)

这篇关于“ let”到底有多精确? Swift中的关键字工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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