Variables are containers used to store data values in a computer's memory.
In Swift, data can be stored in either a variable (which can be changed) or a constant (which cannot be changed).
Swift is highly optimized to encourage the use of constants whenever possible to ensure safe and predictable code.
varYou use the var keyword to declare a variable.
Once a variable is declared using var, you can change its value at any time in the future.
var score = 10
print("Initial score is \\(score)")
// We can update the value later
score = 25
print("Updated score is \(score)")
letYou use the let keyword to declare a constant.
Once a constant is assigned a value, it is locked forever. Attempting to change it will cause a compiler error.
let birthYear = 1998
print("I was born in \\(birthYear)")
// birthYear = 2000 // This would throw an error!
Using let makes your code safer and faster, because the compiler can optimize constants better than variables.
You might notice we didn't specify the data type (like Integer or String) in the examples above.
This is because Swift uses Type Inference. It automatically figures out the data type based on the value you assign to it.
Since 10 is a number, Swift infers that score is an Integer.
If you want to be explicit, or if you want to declare a variable before assigning a value, you can use a Type Annotation.
You do this by writing a colon : followed by the data type.
var welcomeMessage: String welcomeMessage = "Hello from IntricateDevo!" print(welcomeMessage)
Which keyword is used to declare a constant (a value that cannot be changed) in Swift?