问题描述
我在指南中阅读了这个简单的解释:
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
有点像 C 中的 const
指针.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
引用 struct
,则无法更改其属性或调用其任何 mutating func
方法.
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.)
这篇关于“让"到底是怎么回事?关键字在 Swift 中的作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!