In this workshop you learn how to declare and initialize Swift variables and constants. You also learn about common types you can use to annotate a variable or a constant.
|Before you begin, I assume you’ve done the following:
- read workshop 1-13
- launched the Swift Variable app in Xcode 6
- you will use the playground file to practice Swift code presented in this workshop
Declare and Initialize Variables
To declare a variable you use the var keyword like this:
var websiteName = "The App Lady"
var websiteUrl: String = "theapplady.net"
var postTitle: String
On the first line, a string variable was declared. The compiler inferred the variable’s type to be of String because it was initialized with a string literal.
On the second line, a variable was declared and initialized with a string literal. The compiler was informed of the variable’s type by the String annotation. So if I try to put anything other than a string in the websiteName variable or the websiteUrl variable, the compiler will complain.
On the last line, a string variable was declared and annotated with the type String. Attempting to use the variable before initializing it will result in the compiler complaining. So, you should always initialize a Swift variable before using it.
Declare and Initialize Constants
To declare a constant you use the let keyword like this:
let websiteName = "The App Lady"
let websiteUrl: String = "theapplady.net"
let postTitle: String = "Swift Variables and Constants"
You can declare multiple variables and constants on a single line; however, you must separate them with a comma.
var player1 = "Waldo Pablo", player2 = "Jake Hendrickson", let totalPlayers = 2
The only deference between a Swift variable and a constant is that you must initialize the constant when you declare it. Further more, a constant’s value is locked; this mean you can never change its value. If you do so, the compiler will complain.
Common Swift Types
You used the String type to annotate two variables and two constant in above code. You can store text, numbers, and even emojis (picture characters) in a Swift string variable. Now, here is a list of other common Swift types you can use to annotate a variable or constant.
A constant/variable annotated with this type can hold only a single value; be it a letter, an emoji, or a number.
let uppercaseLetter: Character = "M"; var lowercaseLetter = "a"
A constant/variable annotated with this type can hold only an integer value.
let highScore: Int = 287; var lowScore: Int = 28
A constant/variable annotated with this type can hold only a real number.
let payRate: Float = 18.76; var hoursWorked: Float = 18.45
A constant/variable annotated with this type can hold only a real number with greater precision than a Float.
let payRate = 18.76; var hoursWorked = 18.47
A constant/variable annotated with this type can hold an ordered list of values (aka elements). Elements you add in an array must a be of the same type. Further more; elements of an array are zero index. This mean the first element’s index number is zero, the second element’s index number is 1, and so forth.
let fruitNames = ["Apple", "Mango", "Banana"]; var bookChapters = [18, 2, 13, 3, 22]
A constant/variable annotated with this type can hold key-value pairs. The dictionary’s keys must be of the same type. The same goes for the dictionary’s values.
let authorsBooks = ["Ann Rice":"Lasher",
"Daniel Steel":"Going Home",
"Charlaine Harris":"Dead and Gone"]
var ranking = [1: "Gold", 2: "Silver", 3: "Bronze"]
A constant/variable annotated with this type can hold a value of any type, be it an Int, a Character, an emoji, or even a UIButton.
var myObject: AnyObject
myObject = 2349 // an integer value
myObject ="RTy88" // string literal
Special Characters and Symbols
You can use special characters and symbols, such as mathematical symbols, emojis, arrows and other “dingbats,” as a Swift string variable/constant name or as its values. The word emoji means “picture letter” in Japanese. To access special characters and symbols on your Mac computer, use the keyboard shortcut keys (control + ⌘ + Space bar) or Edit | Special Characters… to show the Character Viewer on your screen.
For example, the statement below shows how to declare an emoji variable. Two emojis were used as the variable’s name and it was initialized with the string literal, “umbrellas”.
Displaying Variables Values
When you initialize a variable in the playground file, the compiler automatically display its value in the playground’s Result Bar panel. Say you declared and initialize this variable in the playground’s Code Editor panel:
var userAge = 17
Code below shows 4 ways of displaying the variable’s value in a playground’s Result sidebar.
print("The user is \(userAge) years old")
print() and dump() are Swift functions for printing string literal and variables in the Result Bar panel. You could have use the println() function instead of the print() function. The deference between the two functions is that the println() function prints a newline after it prints objects provided in its brackets (). An example of this is shown below.
print("The user is \(userAge) years old")
“The user is 17 years old”