Variables and Constants in Swift

Become a Subscriber

What is the difference between a constant and a variable and how do you use them?

Open up a new playground and you’ll see an example of a variable declaration

var str = "Hello, playground"

The declaration uses the keyword var which stands for variable. Afterwards we give the variable a name str. Then you have the equal sign, known as the assignment operator = and then you have a string. We will get to strings later, but it is basically what it sounds: a string of characters. Strings need to be enclosed in double quotation marks.

Declaring a constant uses the let keyword. In this case we are going to define a constant π

Note: In Swift you can use any kind of Unicode character or symbol to denote a variable. In this case we are using the mathematical symbol for pi.

let π = 3.14

Constant values cannot be changed after they are declared. For example, if we tried to change the value of our constant π we’d get an error message:

let π = 3.14
π = 3.141516
//error: cannot assign to 'let' value 'π' π = 3.141516

You can even declare multiple variables on the same line by using a comma separator.

var x = 5, y = 6, z = 7

Now what if we don’t want x to store number values, we want it to store a String type. This is when we use what’s called explicit type declarations.

var x : String 

By using the : Type declaration, we can only assign the variable or constant to a value of the type we have explicitly defined. We get an error if we try to set a variable that can take a string value to a number:

var x : String 
x = 5
// error: type 'String' does not conform to protocol IntegerLiteralConvertible'