What are Constants in Swift?
This tutorial assumes that you know how to declare a variable and to work with data types. Well, almost everything is similar between constants and variables, except for two things. If you store a value in constant, it will stay the same throughout the whole program, unlike variables and the grammar (in terms of programming, we call it Syntax).
Talking about syntax, then they pretty much have the same format. The only difference is changing the var keyword with let. For example:
var x = 45 //Variable let pi = 3.14 //Constant
If you are a beginner, you might be wondering where to use var or let. The answer is simple, consider yourself working on a big project in the future where they tell you to name some characters of your game like Fearless Lion, Crazy Monkey, Innocent Cow, etc. Here you will be keeping those values constant because you won't change that names every other time, though it's different when you allow users to set their character's name.
let character1 = "Fearless Lion" //Name of Character 1 let character2 = "Crazy Monkey" //Name of Character 2 var points1 = 500 //Points for Character 1 var points2 = 800 // Points for Character 2
In the above example, you can see the variables declared and not the constants for points because they will keep increasing in the future whenever a player reaches a new level of the game.
To continue the process further, go on to the next most crucial concept called Functions. Till then,
Eat. Sleep. Swift Anytime. Repeat
Want latest weekly iOS updates?
Sign up for our newsletter.