Swift Variables

📦 Swift Variables (Complete Beginner Guide)
🔹 What is a Variable?
A variable is a named memory location whose value can be modified.
✔ Value can change
✔ Declared using var
🔹 How to Declare a Variable
Basic Declaration
Swift automatically detects the type (type inference).
🔹 Variable with Explicit Data Type
🔹 Change Variable Value
🔹 Multiple Variables in One Line
🔹 Variable Without Initial Value
You must specify the type.
❌ Error if used before assigning value
🔹 Variable Naming Rules
✅ Must start with a letter or _
✅ Can contain letters, numbers, _
❌ Cannot start with a number
❌ No spaces allowed
🔹 Swift is Case-Sensitive
🔹 Variable vs Constant
| Feature | Variable (var) | Constant (let) |
|---|---|---|
| Changeable | ✅ Yes | ❌ No |
| Recommended | ❌ Less | ✅ More |
| Safety | Medium | High |
Example:
🔹 Printing Variable Values
🔹 Best Practices 🔥
Prefer
letovervarUse meaningful variable names
Avoid single-letter names (except loops)
Keep variables small in scope
🧠 Summary
var→ changeable dataSwift uses type inference
Type safety prevents errors
Prefer constants for safety
