0
0
Swiftprogramming~5 mins

Let for constants (immutable) in Swift

Choose your learning style9 modes available
Introduction

Use let to create values that do not change. This helps keep your program safe and clear.

When you have a value that should never change, like the number of days in a week.
When you want to avoid mistakes by accidentally changing a value later.
When you want to make your code easier to understand by showing which values stay the same.
When you store fixed settings or constants in your app.
When you want to improve performance by letting the system know the value is constant.
Syntax
Swift
let constantName: Type = value

You can omit the type if Swift can guess it from the value.

Once set, you cannot change the value of a let constant.

Examples
Creates a constant pi with a decimal number. Swift knows it is a Double.
Swift
let pi = 3.14159
Creates an integer constant maxScore with value 100.
Swift
let maxScore: Int = 100
A constant string that cannot be changed later.
Swift
let greeting = "Hello, friend!"
Sample Program

This program shows how to use let to store a constant number of days in a week. Trying to change it will cause an error.

Swift
import Foundation

let daysInWeek = 7
// daysInWeek = 8 // This would cause an error because daysInWeek is a constant

print("There are \(daysInWeek) days in a week.")
OutputSuccess
Important Notes

Trying to change a let constant after setting it will cause a compile-time error.

Use var if you need a value that can change.

Constants help make your code safer and easier to read.

Summary

let creates a constant value that cannot change.

Use it to protect values that should stay the same.

It helps prevent bugs and makes your code clearer.