Swift Constants

Swift Introduction

🔒 Swift Constants (let)

In Swift Constants is a value that cannot be changed after it is set.

Constants are declared using the keyword let.


 What is a Constant?

A constant stores fixed data that remains the same during program execution.

let pi = 3.14

❌ You cannot change it later:

pi = 3.15 // Error

 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

let country = "India"

Constant with Explicit Type

let maxMarks: Int = 100
let temperature: Double = 36.6
let isLoggedIn: Bool = true

Multiple Constants in One Line

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

 Constant Without Initial Value

You can assign only once.

let result: Int
result = 95 // Allowed
// result = 100 ❌ Error

 Constants with String Interpolation

let name = "Sanjit"
print("Welcome, \(name)")

 Constant vs Variable

Feature Constant (let) Variable (var)
Change value ❌ No ✅ Yes
Safety High Medium
Performance Better Normal
Preferred ✅ Yes ❌ Only if needed

Example:

let speedLimit = 80
var currentSpeed = 60
currentSpeed = 70

 Constants with Complex Types

Even if the object is complex, reference cannot change.

let numbers = [1, 2, 3]
// numbers = [4, 5] ❌

⚠️ For collections:

var list = [1, 2, 3]
list.append(4) // Allowed

 Constants in Real-Life Examples

let appName = "SwiftLearn"
let apiURL = "https://example.com"
let maxRetryCount = 3

❌ Common Mistakes

❌ Trying to change a constant:

let age = 25
age = 26 // Error

❌ Using var unnecessarily:

var pi = 3.14 // Should be let

🧠 Summary

  • Use let to create constants

  • Value can be assigned only once

  • Preferred over variables

  • Improves safety & code quality

You may also like...