Swift Variables and Constants

Virtually all programming languages include the ability for programmers to store values in memory using an associated name chosen by the programmer. Variables allow programs to operate on data values that change during the run of the program.

Declaring Swift Variables

A Swift variable declaration uses the following basic syntax:

var <variable name> : <type> = <value>

Given this syntax, a legal declaration for a Pi variable would be the following:

                        var pi : Double = 3.14159

This declaration means: create a variable named pi, which stores a Double data type, and assign it an initial value of 3.14159.

Note

The Swift Standard Library has Pi built in, accessed by using the Float.pi and Double.pi properties.

Variables Versus Constants ...

Get Beginning Swift now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.