What are constants in Swift?

Constants are just like variables except that their value cannot be altered. A constant contains a fixed value that cannot be altered by the program during its execution. Constants can be of any data type defined in the programming language.

Declaring constants

Constants are declared using the let keyword. We can also provide a type annotation while declaring a constant to define the kind of values the constant can store.

import Swift
let firstConstant = 53
print(firstConstant)
// Declaring constant by also providing type annotation
let anotherConstant:Float = 3.14159
print(anotherConstant)

Modifying constants

There is no possible way to alter the value of a constant once we have assigned it a value; doing so would result in an error. The following code shows that if we try to assign a new value to a constant, our program will output an error.

import Swift
let firstConstant = 53
print(firstConstant)
// Modifying the value of the constant
firstConstant = 23
print(firstConstant)
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources