Codementor Events

Variables and Constants in Swift Programming

Published Nov 12, 2018
Variables and Constants in Swift Programming

Variables and Constants

In, swift programming language you might have to store some value so, that you can reuse it again, For example if we want to print “Rahul’s Age” we may use print function like

import Foundation
// Rahul's current Age
print(18)
// Rahul's age Next Year
print("Rahul will be \(18 + 1) next year")
// Rahul's age after two year
print("Rahul will be \(18 + 2) after two years")

So, Rahul’s current age is 18 years. We can print his age using simple print statements. But the the problem is we are repeating yourself if we want to use the Rahul’s age in our program again Remember DRY (Don’t Repeat yourself) when you are coding 😎. So, we can use variables or constants to store Rahul’s age. Let’s start with an example of variables So, the way we create variable is

Var name = value;
var age = 18
print("Current age is \(age) years")
print("Rahul's age will be \(age + 1) after a year")
print("Rahul's age will be \(age + 2) after two years")

So, in this case we are storing the Rahul’s age in age variable that we are further using in our program. Variables are mutable in nature which means that the value stored in the variable can be changed later in the program. Whereas, Constant are very similar to variables we declare it as let but as name suggests it cannot be changed once they are declared. Let’s See what happens when we try to change it

Screenshot 2018-11-12 at 1.33.11 PM.png

When we try to change the value of the age constant by adding one to it. It gives us this error which means that constants cannot be changed they can only be used in our program and immutable in nature.

Discover and read more posts from Vinayak Sareen
get started