๐ŸŽ“ A1Learner
๐Ÿ”

Swift Variables

A variable is a named stored value in a program.

Storing and showing a var

This code stores 10 under a name. The print shows the stored number.

var firstScore = 10
print(firstScore)

Changing a var

The two prints show the count before and after the change. The count grows from 1 to 2 in the output.

var count = 1
print(count)
count = 2
print(count)

A let value

This code gives days the value 7. The print below shows that value.

let days = 7
print(days)

Changing a let fails

The second line tries to change a let value. The compiler stops and names limit in its error.

let limit = 5
limit = 6

Example

var apples = 2
print(apples)
apples = 5
print(apples)

Key points

  • var: a keyword that declares a value that can change.
  • let: a keyword that declares a value that stays fixed.
  • Names in this course use letters and start with a letter.
  • camelCase: a naming style where each later word in a name starts with a capital letter.
  • Use = to give a declared name its value.

In this example, var apples starts with the value 2. The first print shows 2. The next line changes apples to 5. The last print shows 5.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

Which keyword declares a value that can change?