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.

You may want to store a named value in your program that will not change during the life of the program. In the previous example, the value of Pi should never change during the course of a program. How can we ensure that, once defined, this named value can never be accidentally changed by our code?

Swift variables are declared using the var keyword, while Swift constants are declared using the let keyword, for example:

In this code, the named value pi1 is a variable, and its value can be changed by the code after it is declared. The following line of code later in the program would be legal, even though it would result in an invalid value for pi1:

On the other hand, since pi2 was declared as a constant, using the let keyword, the following line of code later in the program would result in a compile-time error, since changing a let constant is illegal:

Generally, any time you create a named value that will never be changed during the run of your program, you should use the let keyword to create a constant. The Swift compiler enforces this recommendation by creating a compile-time warning whenever a var is created that is not subsequently changed.

Swift variables and constants have the same naming rules as most C-inspired programming languages:

When creating variable and constant names in Swift, the generally accepted naming convention is to use a camelCase naming convention, beginning with a lowercase letter. Following generally accepted naming conventions makes code easier for others to read and understand (https://swift.org/documentation/api-design-guidelines/#follow-case-conventions)

For example, the following would be a conventional variable declaration:

var postalCode = "48108"

However, the following would not be conventional, and would be considered incorrect by many other Swift developers:

var PostalCode = "48108"
var postal_code  = "48108"
var POSTALCODE = "48108"

Unlike many other programming languages, Swift is not restricted to the Western alphabet for its variable name characters. You may use any Unicode character as part of your variable declarations. The following variable declarations are legal in Swift:

One of Swift's unique language features is its inclusion of tuples. By default, variables and constants store a single value. Tuples allow a variable or constant name to refer to a set of values. While tuples do not exist in many languages, you can think of them as compound values, and they function almost identically to a structure, which is a single named object which can store more than one variable embedded within it.

By using a tuple, we could take the following variable declaration:

We could combine it to the following:

Then we can access the individual members of the tuple as follows:

Tuple members can also be given individual names, as follows:

Swift functions can accept multiple input parameters, but return only one value. A common use case for a tuple variable type is to include more than one value from a function:

A second way to return multiple values from a function is to use inout parameters, which allows a function to change the value of an input parameter within that function.

While there are valid use cases for changing inout parameter values, returning a tuple has the advantage of returning a value type—rather than modifying input values.

Another unique language feature Swift provides is the optional. In most programming languages, all variables and constants must hold some value. But, in the real world, sometimes a value is unknown. For example, an address may or may not contain a second address line, and more than 60 countries in the world don't use postal codes. Optionals allow variables to indicate whether their value is missing (that is, not assigned), or is truly a blank value.

Optionality for Swift variables is optional (pun intended). To declare a variable as an optional, add a question mark (?) to the end of its data type (or assign another optional variable's value to it so the optional property is inferred from the existing variable).

The following variable name is not an optional:

This next variable name is an optional, and has an initial value of nil:

The presence of the question mark intuitively expresses that the variable may—or may not—contain a string. If the optional is not assigned a value, it will automatically be set to nil, meaning it has no value.

While there are times when force unwrapping variables is safe, you should typically take advantage of Swift's type-safety features by using conditional unwrapping.

With conditional unwrapping, we ask the compiler to first check whether the optional has a value, and return the value if present, or nil if not.

For example, to assign the value of optional a to a new, non-optional variable b, we can use the following code:

This code snippet would print the value 4 to the console. If we had not assigned the initial value 4 to a, then nothing would have been printed.

In Swift, variables are declared before being used. Variables can be declared in various ways, and may not even need to have their type explicitly stated when the compiler can infer data type from initial assignment.

Use an Xcode playground to practice how to declare variables, constants, and tuples.

  1. Launch Xcode as before, and create a new playground named Topic B Summary.playground.
  2. Add the following code to the playground to create three variables storing values related to the weather conditions in Berlin:
    let cityName = "Berlin"
    var humidityPercentage: Double?
    var temperatureCentigrade: Double?

    Note that cityName is a constant, non-optional variable, with an initial string value. Since we know the name of the city in advance, and it doesn't change for this program, it's most appropriate to use let to declare this value as a constant.

    humidityPercentage and temperatureCentigrade are declared as optional, since we do not yet know the weather conditions in Berlin at the start of this program.

  3. Next, add the following line of code to create a tuple to collect the weather report data into a single variable named weather:
    var weather = (city: cityName, humidityPercentage: humidityPercentage, temperature: temperatureCentigrade)

    Recall that providing reference names for each tuple member is optional, but is included here to make the remaining part of the program clearer to other programmers who may need to read this program later.

  4. Next, set the value of humidity within the tuple:
    weather.1 = 0.70

    Note that even though you created a reference name for humidity (humidityPercentage), you can still set the value using the ordinal position within the tuple. The following line of code would probably be better in this case:

    weather.humidityPercentage = 0.70
  5. Now print the tuple to the console. On noticing that the variable provided is a tuple, the console print() function prints all members of the tuple—along with the reference names provided:
    print(weather)

    The output of the print statement is as follows:

    (city: "Berlin", humidityPercentage: Optional(0.69999999999999996), temperature: nil)
  6. Finally, print each of the tuple's components, each on its own line:
    print("City: \(weather.city)")
    print("Humidity: \(String(describing:weather.humidityPercentage))")
    print("Temperature: \(String(describing:weather.temperature))")

    The output of this code is as follows:

    City: Berlin
    Humidity: Optional(0.69999999999999996)
    Temperature: nil