Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
communitycreator

What are constants in Swift?

Mohammad Razi ul Haq

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)

RELATED TAGS

swift
communitycreator

CONTRIBUTOR

Mohammad Razi ul Haq
RELATED COURSES

View all Courses

Keep Exploring