4: Constants in Swift

Constants are same like variables which help to store data value in it but they are different in one way that once you have assigned value to constant, the value will remain the same till the end of the application life time. For variable declaration, Swift provides keyword var and for the constant declaration, Swift provides the keyword let, rest is the same.

As compare to other languages, constants are always encouraged and you will see extensive use of constants in Swift.

Declaring a constant in Swift

In swift, you can declare a constant with keyword “let”.

let name
let emailAddress
let age

You can assign any value to the declared constant but you cannot change or update constant value. Type of the constant depends on the value which you will assign to it. If you write

let name = "Khan"

It will become string type constant.

let age = 10

it will become integer type of constant.

You can declare boolean constant as well with

let myBoolean = true
let myBoolean = false

 

Explicitly declared constant (Type Annotation)

Swift also provides functionalities to declare specific type of constant with “type annotation” let constant_name : DataType

let myInteger   : Int
let myString    : String
let myFloat     : Float

Once constant are declared, you can assign values to them.

myInteger = 10
myString  = "Hello"
myFloat   = 12.123

Swift also allows to declare and define explicit data type at same time.

let myIntAndValue : Int = 10
let myStringAndValue : String = "Hello"

 

Why constant

Constants provide a safety feature, once you have assigned a value to constant, you will not change its value mistakenly. Some values are fixed for ever and you must not change these in any circumstances.

Example 1:
You are writing a small mathematical program to “calculate the radius of a circle from its area” and you need value of pi which is 3.14159. You must declare it as a constant not a variable because its a fixed value and it would not and should not change in any situation.

let pi = 3.14159

Example 2:
You have created a table in database called “StudentRecord”. This table would have information about all students registered in school. The data about student may or may not change in this table but the table name must not change.

let tableName = "StudentRecord"

 

Download file from GitHub