Swift Constants
Constants store values that, once set, never change; Swift declares constants with let.
The declaration syntax for let and var is nearly identical; the only difference is whether reassignment is allowed: let can be assigned only once.
This article covers let's immutability semantics, what it really means for reference types, deferred initialization, naming conventions, and the guidelines for choosing between let and var; see 《 for var usageSwift Variables》。
Declaring constants with let
let declares a constant that can be assigned only once; after initialization its value is fixed.
The declaration is identical to var; just swap the keyword.
Example
import Foundation
// let declares a constant: it can't be changed after assignment
let site
=
"www.runoob.com"
let visits
=
100
let price
=
9.9
(
"Site (site) visits: (visits), unit price: (price)"
)
Running result:
站点 www.runoob.com 访问量:100,单价:9.9
If you assign a let-declared constant a second time, the compiler reports an error outright and the code won't compile.
Example
let site
=
"www.runoob.com"
site
=
"RUNOOB"
Compiler error (only the two key lines are shown; the actual output also prints the error location):
error: cannot assign to value: 'site' is a 'let' constant
note: change 'let' to 'var' to make it mutable
This error appears at compile time rather than crashing at runtime, which is exactly the "safety" Swift emphasizes.
let restricts the binding, not the object
This is the most misunderstood point about let: it restricts "this binding can't point to another value," not "the object it points to can't change at all."
For reference types, an instance declared with let can still modify its own properties; you just can't make it point to a different instance.
Example
import Foundation
// Reference type: let restricts the binding, not the object itself
class
Counter
{
var value
=
0
}
let counter
=
Counter
(
)
counter.
value
=
10
(
"counter.value ="
, counter.
value
)
// counter = Counter() // illegal: can't point to another instance
Running result:
counter.value = 10
Value types behave differently. For value types such as structs, arrays, and dictionaries, an instance declared with let is entirely immutable—even its internal properties can't be changed.
Example
struct
Site
{
var name
=
"RUNOOB"
}
let site
=
Site
(
)
site.
name
=
"Runoob"
Compiler error (only the two key lines are shown):
error: cannot assign to property: 'site' is a 'let' constant
note: change 'let' to 'var' to make it mutable
After changing let to var, site.name = "Runoob" becomes legal, so the claim "a struct's value can't be modified" holds only when it's declared with let.
| Scenario | Can it be modified after a let declaration | Description |
|---|---|---|
| Internal properties of a value type instance | No | Structs, arrays, and dictionaries are entirely immutable |
| Properties of a reference type instance | Yes | The object's own state can change |
| Reassigning a reference type instance | No | The binding is immutable and can't point to a new instance |
Note:For the full difference between value and reference types, see 《Swift Value Semantics and Copy-On-Write》; class definitions and properties are covered in 《Swift Classes》.
Deferred initialization of constants
A constant doesn't have to be assigned on the line it's declared; you can declare just the type and assign it later.
This is called deferred initialization, but note: let can be assigned only once, and every branch must guarantee it's eventually assigned.
Example
// Declare first, assign later: let can also be initialized lazily, but only once
var input
=
85
let score
:
Int
if
input
=
60
{
score
=
input
}
else
{
score
=
0
}
(
"score ="
, score
)
Running result:
score = 85
The compiler checks all branches; if one misses the assignment, it reports a "constant not initialized" error.
The most common use of deferred initialization is when a value depends on a condition to be computed, yet you want it to stay unchanged once declared.
Note:Deferred initialization is not lazy. Here, let can't be read before assignment, whereas lazy is computed on first access and is a kind of property modifier, covered in 《Swift Properties》.
Constant naming conventions
Swift names constants with lowerCamelCase just like variables, unlike the C and Java habit of ALL_CAPS_WITH_UNDERSCORES.
Although ALL-CAPS compiles in Swift, it doesn't follow community conventions and is usually flagged in code review.
| Rule | Recommend | Not recommended |
|---|---|---|
| lowerCamelCase, starting with a lowercase letter | maxRetryCount | MaxRetryCount、MAX_RETRY_COUNT |
| Use descriptive names, not single letters | defaultTimeout | t、n |
| Start Boolean constants with is or has | isDebugEnabled | debug |
| Avoid keywords; use backticks only when necessary | className | class |
Using UpperCamelCase for type names and lowerCamelCase for variables and constants is the most basic and consistent convention in Swift.
If a constant belongs to a type rather than being globally shared, prefer writing it as a static let inside the type to avoid polluting the global namespace; see 《 for detailsSwift Properties》。
Guidelines for choosing between let and var
The community habit is to prefer let and switch to var only when modification is truly needed, minimizing mutability and making code easier to reason about.
The key to the choice is readability and safety, not performance, so there's no reason to loosen mutability for the sake of "flexibility."
Example
// Use let for things that don't change
let siteName
=
"RUNOOB"
let maxRetryCount
=
3
// Use var for things that do change
var retryCount
=
0
retryCount
=
1
(
"(siteName): retried (retryCount) times, limit (maxRetryCount) times"
)
Running result:
RUNOOB:已重试 1 次,上限 3 次
If unsure, write let first and change to var only when the compiler says "cannot assign to value," ensuring every var has a reason.
| Case | Choice | Description |
|---|---|---|
| Value doesn't change once determined | let | The default choice; config items and fixed text fall here |
| Needs repeated assignment | var | Counters, accumulators, state flags |
| Needs deferred assignment | let | Declare the type first, then assign once |
| A reference type object's state must change | let | The object is mutable internally; the binding itself doesn't need var |
Common questions
Below are the most common questions about constants.
Can you add elements to an array declared with let
No. Array is a value type, so an array declared with let is immutable; calling append is an error, so you must use var.
Example
var names
=
[
"Runoob"
]
names.
append
(
"RUNOOB"
)
(
names
)
let fixed
=
[
"Runoob"
]
fixed.
append
(
"RUNOOB"
)
Compiler error (only the two key lines are shown):
error: cannot use mutating member on immutable value: 'fixed' is a 'let' constant
note: change 'let' to 'var' to make it mutable
When should you use let
Use let by default and change to var only when the compiler tells you modification is needed—this is the most common advice in the Swift community.
Can a constant be assigned lazily
Yes—just declare the type and assign once later, but every branch must guarantee assignment or the build fails.