Mutable Variables

In the following lesson, you will learn how to declare a mutable variable.

We'll cover the following

Mutable is defined as something that can be altered, and mutable variables are just that; variables whose values can be altered.

Declaring a Mutable Variable #

To declare a mutable variable, we use the var keyword. Let’s take the same example we used in the previous lesson. We have a variable message which is assigned a String value.

Press + to interact
var message: String = "Hello World"
// Driver Code
println(message)

Now let’s assign a new value to the variable.

Press + to interact
var message: String = "Hello World"
message = "Hello Educative"
// Driver Code
println(message)

After executing the above code, you will see that in the output, the new message “Hello Educative” is displayed.


Now that we know how to declare variables, let’s move on to some basic datatypes.