As Apple Documentation says:
Use
let
to make a constant andvar
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.
Let's consider some class:
class A {
var a = [String]()
}
Since array a
is mutable, it's defined via var
. But what if we consider class B, where instance of A is property?
class B {
let b = A()
}
Even if b
is mutable, let
keyword will be ok, because reference won't be changed. On the other hand, var
will be ok too, because content of b
can be changed. What should I pick in this example - let
or var
?