How exactly does the "let" keyword work in Swift?

constants, swift

Solution

`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` 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.

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`.

(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.)

Problem

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. 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?

Original source

Related problems