Swift Constants
🔒 Swift Constants (let)
Constants are declared using the keyword let.
What is a Constant?
A constant stores fixed data that remains the same during program execution.
❌ You cannot change it later:
Why Use Constants?
Swift strongly encourages using constants because they:
-
✅ Improve safety
-
✅ Prevent accidental changes
-
✅ Make code more readable
-
✅ Improve performance
👉 Rule of thumb: Use let by default, var only if value changes
How to Declare Constants
Basic Constant
Constant with Explicit Type
Multiple Constants in One Line
Constant Without Initial Value
You can assign only once.
Constants with String Interpolation
Constant vs Variable
| Feature | Constant (let) |
Variable (var) |
|---|---|---|
| Change value | ❌ No | ✅ Yes |
| Safety | High | Medium |
| Performance | Better | Normal |
| Preferred | ✅ Yes | ❌ Only if needed |
Example:
Constants with Complex Types
Even if the object is complex, reference cannot change.
⚠️ For collections:
Constants in Real-Life Examples
❌ Common Mistakes
❌ Trying to change a constant:
❌ Using var unnecessarily:
🧠 Summary
-
Use
letto create constants -
Value can be assigned only once
-
Preferred over variables
-
Improves safety & code quality
