Workshop 18: Array

In this workshop you will learn the basics of declaring, initializing, and accessing elements of a swift array. You will also learn how to manipulating elements of an array.

Before you begin, I assume you have done the following:

workshop16-fig00

A Swift array is a collection of elements of the same type. When discussing Swift array, there are some key terminology you should know about.

Element

Refers to a value in the array. For example, an array of 6 Strings is said to have 6 elements. An array of 50 Floats has 50 elements and so on…

Index

Refers to the location of an element in the array. Index is also know as a position number, or more formally, as a subscript. The first element in an array is represented by an index or subscript of 0 (zero). For example, fruitNames[0]. This first position is known as the zeroth element. The second position is referred to by fruitNames[1].

nsarray_index
Figure 1: A String array

Creating an Empty Array Variable

Here are two ways to create an empty array variable.

var fruitNames: [Int] = []
var fruitNames: Array = []
// Output in a playground file
0 elements
0 elements

 Adding Elements in an Array Variable

Once you’ve created an array variable, you have to add elements in it before you can use it. Code below shows four ways to add elements in an array variable.

// Declare and initialize a String array variable
var fruitNames = ["Avocado", "Mango", "Water Melon"]
fruitNames.append("Peach")
fruitNames.insert("Grape", atIndex: 0)
fruitNames += ["Fig", "Dragon Fruit"]

The second statement added an element to the end of the array. The third statement added an element at the first position in the array. The fourth statement added to more elements to the end of the fruitNames array, and it have these 7 elements now:

[“Grape”, “Avocado”, “Mango“, “Water Melon“, “Peach“, “Fig“, “Dragon Fruit“]

Add an Array in an Array Variable

You can add new array in an existing array element like this:

// Declare and initialize two array variables
var arrayOne = [1024, 1025, 1026, 1027]
var arrayTwo = [1028, 1029]

// Add arrayTwo to arrayOne
arrayOne += arrayTwo

// arrayOne now have these 6 integer elements now.
[1024, 1025, 1026, 1027, 1028, 1029]

Accessing The Array Variable Elements

Once, you’ve added elements in an array, you can access its elements via code shown below.

fruitNames[2]
fruitNames[fruitNames.count - 1]
fruitNames[1...3]

Assuming the fruitNames array has these elements:

var fruitNames = ["Grape", "Avocado", "Mango", "Water Melon", "Peach"]

The first statement above accessed the third element in the array-Mango. The second statement accessed the last element in the array-Peach. The third statement accessed the second, third, and fourth elements of the fruitNames array, resulting in this output in the playground:
[“Avocado”, “Mango”, “Water Melon”]

Querying an Array Variable

Here are two Swift properties and a method you can use to query an array.

Code below shows how to use above properties and method.

fruitNames.isEmpty
fruitNames.count
let fruitNameIndex = find(fruitNames, "Apple")
if let actualIndex = fruitNameIndex {
    println("Found \(fruitNames[actualIndex]) at index \(actualIndex)")
} else {
    println("Element not found!")
}

Assuming the fruitNames array has these elements:

var fruitNames = ["Grape", "Avocado", "Mango", "Water Melon", "Peach"]

The first statement above check to see if the fruitNames has any elements. Since it does, the isEmpty property returns false. The second statement return the number 5 because the array has 5 elements.

The third statement used the find() function to find out whether the fruit name, “Apple” exist in the fruitNames array or not. Since it doesn’t, the find() function return the optional value, nil and it is assigned to the fruitNameIndex constant. The keyword nil means nothing or zero. If the fruit name did exist in the array, then the find() method would have returned the index position of the fruit name; which is an optional value. For example, if “Apple” was at index 3 in the fruitNames array, the find() function would have return this optional value: {Some 3}.

The fourth statement on line 4 unwrapped the optional value, the find() method returned and put it in a constant called, actualIndex. The if block’s statement is executed only if the actualIndex constant was initialized with an optional value other than nil; for example, the optional value: {Some 3}. The else block’s statement is executed only if the actualIndex constant was initialized with the optional value nil.

Change an Array Variable Element

To change an element in an array variable, you use the array’s index position or the range positions, as demonstrated in code below.

fruitNames[3] = "Passion Fruit"
fruitNames[1...3] = ["Guava", "Coconut", "Banana"]

The first statement change the third array element from “Water Melon” to “Passion Fruit”. The second statement changed the second, third, and fourth array elements from this:
“Avocado”, “Mango”, “Passion Fruit”

to this:
“Guava”, “Coconut”, “Banana”

Delete Elements from an Array Variable

You can use these functions to delete an element from an array variable.

Code below shows how to use above functions on the fruitNames array.

// Declare and initialize an array variable with 5 elements
var fruitNames = ["Grapes", "Avocado", "Mango", "Water Melon", "Peach"]
fruitNames.removeAtIndex(2)
fruitNames.removeLast()
fruitNames.removeAll()

Reverse Elements in a Variable Array

I don’t know why you’d want to, but you can reverse elements in a variable array by using the reverse() function like this:

// Declare and initialize an array variables
var arrayOne = [1024, 1025, 1026, 1027]

// Reverse the array's elements
arrayOne.reverse()

// Output in a playground file
[1,027, 1,026, 1,025, 1,024]

Joining Array Variables

If you want to join elements in two different arrays; then use the + operator.

// Declare and initialize two array variables
var animals = ["Dog", "Cat", "Cow", "Horse", "Lion"]
var sounds = ["bark", "Meow", "Moo", "Neigh", "Roar"]

// Join the arrays elements
animals += sounds
// Output in a playground file
["Dog", "Cat", "Cow", "Horse", "Lion", "bark", "Meow", "Moo", "Neigh", "Roar"]

Constant Array

You can declare and initialize a constant array like this:

let animals = ["Dog", "Cat", "Cow", "Horse", "Lion"]
// or like this
let animals: [String] = ["Dog", "Cat", "Cow", "Horse", "Lion"]

However, you cannot add, modify, or delete elements in an array constant. You can only do the following to a array constant:

animals[2] // Access an element
animals.isEmpty // Check to see if the array is empty
animals.count // Count the array elements
find(animals,"Cat") // Find an element
animals.reverse() // Reverse elements in the array