LEARN SWIFT

Buy the PDF

Chapter 4 Constants and Variables

In Swift all values are strictly typed. This has two implications that are a significant change to what you are accustomed to if you’ve been previously using a dynamically typed language.

  1. You must declare the type of all of your variables and constants, or else assign them an initial value which Swift will use to infer their type.
  2. You can’t change the type of a variable once you’ve declared it. Its type is fixed at the time it is declared. For constants, their value is also fixed and can’t be changed once they’ve been initialized.
Listing 4.1: Constants and Variables.
1 var lives = 9
2 let name = "TopCat"
3 
4 lives = lives - 1
5 lives
6 
7 name = "TomCat" // Error
8 lives = "NotAnInt" // Error

In Swift you declare a variable using the var keyword and constants using the let keyword.

Constants are immutable. Once you’ve declared them, they cannot be changed again. Attempting to modify a constant in any way will result in an error.

Variables are mutable - you can change their values (but not their type).

For example in Listing 4.1 name is immutable, whereas lives is mutable.

I can change the value of lives by assigning a new value to it (line 4). Whereas if I try to change the value of name, I get an error (line 7).

While I can change the value of a variable, I can’t change its type. If I try to assign a value of a different type to a variable, I’ll get an error. For example, at line 8, trying to assign a string to lives results in an error. When we initially declared lives at line 1 we initialized it with value 9. As a result, Swift inferred that lives in an integer. Swift is strict about typing. The type of lives is fixed as an integer at the time of its initial declaration, so we can’t change it to something else and we can’t assign a value to it that isn’t an integer. We’ll talk more about types and type inference in Swift in chapter 5.

4.1 Unicode in variable names

Interestingly, you can also use unicode characters in your names. Here’s an example using unicode characters as variable names. (You can access the character palette using C-⌘-space in Xcode)

let π = 3.14
let r = 2.5
print(π * r * r)  // "19.625"

I’m not sure how useful this is, but it might be useful to include symbols in some variable names to make them more illustrative or to improve the readability of your code.