Swift Variables

Swift Variables and Constants

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.


Creating Variables with var

You 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.

Variables Example:

var score = 10
print("Initial score is \\(score)")

// We can update the value later score = 25 print("Updated score is \(score)")


Creating Constants with let

You 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.

Constants Example:

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.


Type Inference

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.


Type Annotation

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.

Type Annotation:

var welcomeMessage: String
welcomeMessage = "Hello from IntricateDevo!"
print(welcomeMessage)

Exercise

Which keyword is used to declare a constant (a value that cannot be changed) in Swift?