Optional Variables in Apple Swift

Last update: October 26, 2016

Swift is Apples new programming language for iOS, OS X, watchOS, and tvOS app development. The current version is 3.0. Swift provides its own versions of all fundamental data types :

  • Int for integers
  • Double for 32 bit decimals (floating-point values)
  • Float for 64 bit decimals (floating-point values)
  • Bool for Boolean values
  • String for text

Integers are either signed (positive, zero, or negative) or unsigned (positive or zero). Integer literals can be written as:

  • A decimal number, with no prefix
  • A binary number, with a 0b prefix
  • An octal number, with a 0o prefix
  • A hexadecimal number, with a 0x prefix

Floating-point literals can be decimal (with no prefix), or hexadecimal (with a 0x prefix). Decimal floats can also have an optional exponent, indicated by an uppercase or lowercase e.

Swift also provides powerful versions of the three primary collection types :

  • Array
  • Set
  • Dictionary

Swift differentiates between constants and variables. The value of a constant cannot be changed once it is set, whereas a variable can be set to a different value in the future. Constant and variable names can contain almost any character, including Unicode characters.

let π = 3.14159
你好 = "你好世界"
🐶🐮 = "blablabla"

Constants are declared with the keyword “let”.

let myName = "Marco"

Constants are also called immutable because they cannot be changed after you have stored data in them.

Variables are declared with the keyword “var”. Variables are called mutable because you can constantly change the data that they store.

var x = 1.2

There are several possibilities to define a variable or a constant :

implicit :

var yourName = "Oscar"

explicit :

var yourName: String = "Oscar"

separated :

var yourName: String
yourName = "Oscar"

multiple line :

var x=1.2, y=3.4, z=5.6

typealias :

typealias FirstName = String
var hisName: FirstName = "Jeannot"

computed (getter) :

var number: Double {
  get {
    return x + y + z
    }
}

Swift is a type-safe language, which means the language prevents you from passing by mistake a wrong data type to a variable. Data Types can be converted with the functions Int( ), Double( ), Float( ), …

When a variable is declared, it can’t be used until data is stored in it, otherwise the program fails. Initially storing dummy data in a variable can cause errors. Therefore Swift uses the concept of optional variables. If an optional variable contains nothing, it’s considered to hold a value called nil. To create an optional variable, you declare it with its datatype, followed by a question mark :

var ourName : String?

Storing data in an optional variable is not different than storing data in an ordinary variable.

ourName = "Simone"

Retrieving data from an optional variable is however different and requires additional steps. After checking that the optional variable contains data, you have to unwrap it to get the actual data.  Unwrapping is done with the exclamation mark :

print(ourName!)

If you retrieve an optional variable containing a nil value the program will fail. Therefore we must first check that it contains data. This can be done in two ways :

explicit check

if ourName != nil {
   // retrieve value with ourName!
} else {
   // do something else
}

optional binding (constant assignment)

if let rumpelstilzchen = ourName {
  // retrieve value with rumpelstilzchen or ourName!
}

Optional variables are at the heart of many of Swift’s most powerful features. Once you understand the concept, they are very useful to link a user interface item to Swift code with IBOutlet variables.

A common user interface are text fields that are often empty at the program start. If a IBOutlet is defined as optional variable as follows

@IBOutlet weak var labelText: NSTextField?

we need to use the exclamation mark every time we want to access the data stored in this variable, which can be error prone and make the code hard to read. If we define the IBOutlet variable as an implicit unwrapped optional variable with an exclamation mark

@IBOutlet weak var labelText: NSTextField!

we can access it without question mark if it contains a value. In the case of IBOutlets Xcode catches any potential error, but this is not the case for other potential variables where you need to check and unwrap yourself the data.