Link Menu Expand Document

🔴 CONSTANTS

//constants
let name: dataType = value

Swift Programming

Swift Programming

Xcode

iOS


Variables vs Constants

The key difference between variables and constants is variables allow you to change the value inside the variable during the execution of the program (meaning while the app is running), and constants do not. Once values are set in constants, any change will result in a compile time error.

To create a constant, use the let keyword instead of var

// constant
let lightSwitch = true 

And that’s it! All the same rules apply.

Let’s see it in practice: Show the screenshot. and as you see here, the error states the value is immutable meaning the value cannot mutate/ change.


When to use constants

Use constants when we are absolutely certain that value will not change during the execution of the program. Now, you may be thinking, why not just create everything as variables instead? Both will work but here are the advantages of using constants.    First, it helps with readability. Meaning when you read your code or someone else does, they will immediately know this constant value will NEVER EVER CHANGE and should NOT change.    By setting constants, we tell the compiler to set off errors if something in our code does try to change it. This makes it easy for us to debug and fix our code in the future. If we didn’t create it as a constant, it would make it very hard to catch otherwise.    The code written is more CLEAR for everyone and presents a more safe way to write code. Just remember, the effort you place now of writing clean code will save you hours of headache and debugging time for you and your fellow coworkers. Always keep that in mind. It will always catch up to you.

Quick look:

var is a keyword that tells the compiler we’re creating a variable.
name is the name of our variable.
: separates the name and the data type.
String is the data type of our variable.
= is assignment operator.
value is the value we assigned to our variable.