Swift Variables and Constants Example

1. Introduction

In Swift, variables and constants are foundational concepts. A variable, declared with the var keyword, holds a value that can be changed after it's been set. Conversely, a constant, declared with the let keyword, holds a value that cannot be changed once it's been set. This distinction ensures clarity and intent in your code.

2. Source Code Example

// Declaring a variable
var myVariable = 10
print("The value of myVariable is \(myVariable)")

// Changing the value of a variable
myVariable = 20
print("The updated value of myVariable is \(myVariable)")

// Declaring a constant
let myConstant = 30
print("The value of myConstant is \(myConstant)")

// Uncommenting the next line will result in a compilation error
// myConstant = 40

Output:

The value of myVariable is 10
The updated value of myVariable is 20
The value of myConstant is 30

3. Step By Step Explanation

1. A variable named myVariable is declared and initialized with a value of 10. This is then printed to the console.

2. The value of myVariable is updated to 20 and the updated value is printed.

3. A constant named myConstant is declared and initialized with a value of 30. This value is then printed. Unlike myVariable, the value of myConstant cannot be changed once it's been set, ensuring the immutability of the constant.

4. Any attempt to change the value of myConstant after its initial assignment will result in a compilation error. This ensures that the value remains constant throughout the lifecycle of your program.


Comments