Swift Variables

Swift Introduction

📦 Swift Variables (Complete Beginner Guide)

In Swift Variables is used to store data that can change during program execution.

🔹 What is a Variable?

A variable is a named memory location whose value can be modified.

var age = 25
age = 26

✔ Value can change
✔ Declared using var


🔹 How to Declare a Variable

Basic Declaration

var name = "Swift"

Swift automatically detects the type (type inference).


🔹 Variable with Explicit Data Type

var score: Int = 90
var price: Double = 99.99
var isActive: Bool = true
var language: String = "Swift"

🔹 Change Variable Value

var city = "Delhi"
city = "Mumbai" // Allowed

🔹 Multiple Variables in One Line

var x = 10, y = 20, z = 30

🔹 Variable Without Initial Value

You must specify the type.

var result: Int
result = 100

❌ 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

var userName = "Sanjit" // ✅
var _count = 5 // ✅
var 1value = 10 // ❌

🔹 Swift is Case-Sensitive

var age = 20
var Age = 25 // Different variable

🔹 Variable vs Constant

FeatureVariable (var)Constant (let)
Changeable✅ Yes❌ No
Recommended❌ Less✅ More
SafetyMediumHigh

Example:

let country = "India"
// country = "USA" ❌ error

🔹 Printing Variable Values

var marks = 88
print(marks)
print("Marks: \(marks)")

🔹 Best Practices 🔥

  • Prefer let over var

  • Use meaningful variable names

  • Avoid single-letter names (except loops)

  • Keep variables small in scope


🧠 Summary

  • var → changeable data

  • Swift uses type inference

  • Type safety prevents errors

  • Prefer constants for safety

You may also like...