By Tanmay Bakshi

This article, excerpted from chapter 7 of Hello Swift!, tells you what an array is and gives quite a few examples of how one can be used.

Save 37% off Hello Swift! with code fccbakshi at manning.com.

What is an array?

An array is a group of multiple variables of the same kind. Consider this example:


Figure 1 Array of names


If you wanted to create this array in code, you could do this:

  
 var arrFriends: [String] = [“Frank”, “Amy”, “Maya”, “Tom”]
  

The line of code above is an example of creating an Array, with String values in it. The square brackets ( [] ) around the “String” in the type of the variable tell Swift that this is an Array. Then, the code sets values inside of the array to Frank, Amy, Maya, and Tom.

In the real-life example, you give each student a slip of paper with a number. But in this code, there aren’t any numbers.

That’s the cool thing about arrays, when you put values into it, the array assigns the numbers for you. So in this example, these four students end up with numbers assigned, in the order that they’re added to the array!

IMPORTANT!!!

Now, I have to tell you something which is both important and confusing. Arrays start counting with 0, not 1. If you think back to the example of the students in class getting slips of paper, the first slip given out will say 0, not 1. If ten slips are given out, they’ll be numbered: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. In fact, it makes sense because Integers start with 0. It may seem a little weird at first, because in school, we learn to count from 1. We almost forget about Zero! (poor zero…)

You have an array with values. And this helps you because it’s easy to get the values back out of the array, in order.

Think back to the earlier example about the students with numbered slips of paper. Pretend that it’s time for the next student to give a report. The teacher might not remember who’s next in line, but he knows that the last student who did a report was number 2, and all he has to do’s call on number 3.

To get the name of someone stored in the array you created, you also (in code) use the number. In programming, this number is called the index.

In order to access some value (friend’s name) from the array, you must type in the name of the array, then [<index>]. To retrieve the first name from the array:

  
 print(“\(arrFriends[0])”)
  

This makes sense, because “Tim” is at index 0 of the array. Note here that the array indexes start with 0, as 0, 1, 2, 3… The indexes don’t start with 1 as 1, 2, 3… the index of an array starts at 0, not at 1!


Figure 2 Array of names, positions and indexes


What if you didn’t know the index number? What would you do? Well, you’ll learn this soon. Hint: You’ll loop through, check values, and find the index.

Getting to your data

Now, let’s start the official lesson: How do I get to my data?

In order to get to your data, you need to know the index number to that specific entry. Let’s say you make a list of your friends’ names in the form of an array. You want to access “Bob” from that list.

Try it yourself

Try these code examples out in the playground!

  
 var arrPets: [String] = [“dog”, “cat”, “fish”, “hamster”]
  
 print(“\(arrPets[2])”)
  

In the playground, it should print “fish”.

Wait, you’re grabbing the value at index 2, why is that “fish” and not “cat”?

Remember, in programming, most ranges start with 0, not 1. If I accessed index 1, I’d get “cat” which is, in fact, the second value in the array. If I accessed index number 0, I’d get “dog”, the first value in the array. “Fish” is at index number 2.


Figure 3 Array of pets, positions, indexes, and the print commands


POP Quiz

Take a look at these arrays:

  
 var food: [String] = [“pizza”, “burger”, “salad”, “fries”]
 var bigNumbers: [Int] = [53000, 24789, 6093, 4949493]
  

What do you think gets printed with these print() commands?

  
 print(“\(bigNumbers[2])”)
 print(“\(food)”)
 print("\(food[4])")
  

The first print command prints out 6093. Did you notice that this array contains integers, and not strings?

The second print command prints out all the values in the food array! Try it out!

The third print command gives you an error, because it’s trying to print the FIFTH value and there are only four.

TIP

You can create an array of integers. You need to use the keyword Int and leave off the quotes around the values!

Altering the Array

Now, you’re going to store and change data in arrays with programming!

Let’s start off with changing one of the names of your friends. The existing array of friends is:

  
 var arrFriends: [String] = [“Tim”, “Frank”, “Ann”, “Maya”]
  

Ok, now what if you need to replace Maya with Tommy? How do we change that name in the array?

First, you need to know the index that Maya’s name is at. Maya’s name is the fourth one in the list. That means that name is at index number 3.

REMINDER

You know that the index starts with 0, not 1, right? The fourth name in the list has an index of 3!

You can do this:

  
 print(“\(arrFriends[3])”) 
 arrFriends[3] = “Tommy”   
 print(“\(arrFriends[3])”) 
  

❶   We want to see what is at index 3 to make sure it contains Maya.

 Here, we change the name stored at index 3 to Tommy.

❸  Now we print the name at index 3 again to see that it has been successfully changed to Tommy.

At line “#B”, we set the third index of the arrFriends array to Tommy like we change the value of any other variable.

Try it yourself

In this playground exercise, you’ll make an array that lists some of the games you like. Then, in the next section, you’ll loop through it.

To start, open up Xcode and create a new playground.

Name this Playground “arrays_in_Swift”. Then, remove the first line and type the array code and five games, for example:

  
 var gamesILike: [String] = [“Basketball”, “Soccer”, “Hockey”, “Tetris”, “Pacman”]
  

If you want to access the values of the array, you could type:

  
 print(“\(gamesILike[0])”)
 print(“\(gamesILike[1])”)
 print(“\(gamesILike[2])”)
 print(“\(gamesILike[3])”)
 print(“\(gamesILike[4])”)
  

What do you do if you want to add another game to the array? In addition to editing values that are already in the array, you can also add more values. To do this, you use the “.append” function (method) on an array.

Here’s an example:

  
 var gamesILike: [String] = [“Basketball”, “Soccer”, “Hockey”, “Tetris”, “Pacman”]
  
 gamesILike.append(“Agar.io”)
  

You can use “.append” after the name of the array along with the value that you want to append to the array, and it gets added to the array. Remember that as the function name append says, the name of this game will be put at the end of the array.

The array, after running this command, will contain this:

  
 [“Basketball”, “Soccer”, “Hockey”, “Tetris”, “Pacman”, “Agar.io”]
  

Looping Through Arrays

Now for the most interesting part of arrays: Looping through your arrays!

Let’s say you create an array, and you want the names of your friends in it, again. Here’s that array:

  
 var arrFriends: [String] = [“Tim”, “Bob”, “Frank”, “Tommy”, “John”]
  

Now let’s say you wanted to print every single friend’s name in the array. How would you do it, if you didn’t want to list them all out by running print() five times, with the index changed each time? And imagine if the array had 100 values in it!

To do this, you can loop through the array, and print every single value in the array as you loop.

In order to do this, you’ll make use of what you know about loops and combine it with what you learned now.

“For in” loops are amazing for iterating or looping through arrays, right? You’re about to find out for yourself.

The syntax of looping through an array is:

  
 for <variablename> in <arrayname> {
     <do something>
 }
  

Here’s what all of that means:

Table 1 Syntax definitions for the “for in” loop with arrays

Part of Syntax

Definition

<variablename>

This is the name of the variable which is incremented each time in the loop.

But wait! For an array, we don’t need to put a range to loop from and to.

What will this variable be equal to and when will it end? Stick around to find out!

<arrayname>

This is the name of the array that you want to loop through.

<do something>

Here you can write any code you want to run! This is the block of code that gets repeated.

 

Wait, I remember the “for in” loop uses a range that tells it how many loops to do, but this doesn’t have one. How does it know how many loops to make?

The “for in” can figure out how long the array is without you telling it. Instead of <variablename> having the value of a number_from to number_to, it’ll know the length of the array! In the following code example, the code in the loop prints out the names of our friends, not 0, 1, 2, 3, 4.

Next, this loops through the friends array and prints out every name in it:

  
 var arrFriends: [String] = [“Tim”, “Bob”, “Frank”, “Tommy”, “John”]
  
 for friendname in arrFriends {
     print(friendname)
 }
  

BUT WAIT! I didn’t put the quotes and brackets around the “friendname” as “\(friendname)” in the print() statement, so it couldn’t possibly work! Or will it?

 

***EXTRA SPECIAL TIP***  You can print variables with print(), without having to ever put the quotes! It’s completely valid to say: print(i)! Try it yourself!

 

NOTE You can put any valid variable name in a “for” statement! Instead of having to use “friendname”, you could even use “i”, “x” or “myFriends” without the quotes.

You’ll see this output after running that code:

Tim

Bob

Frank

Tommy

John

Notice that you don’t have to use five different variable names to store or print your friends’ names!

As you can see, loops help us when we’re dealing with lots of array elements, in an efficient way, instead of needing to use a bunch of variable names.

Now that you’ve seen how arrays work, it’s time to create an app.

APP 10 Number Sorter

Getting Started

This app lets the user enter ten different numbers. The app sorts them from small to large.

NOTE When you sort from small to large, like from one to five, is known as ascending order. If you sort from five to one, it’s called descending order.

To begin, create a UI like this one:


Figure 4 The 10 Number Sorter UI!


Coding the App

Great! Next, modify your code to look like this:

Code Listing 1 The 10 Number Sorter code

  
 class ViewController: UIViewController {
  
    
     @IBOutlet var textfield1:  UITextField!               
     @IBOutlet var textfield2:  UITextField!                       
     @IBOutlet var textfield3:  UITextField!                       
     @IBOutlet var textfield4:  UITextField!                       
     @IBOutlet var textfield5:  UITextField!                       
     @IBOutlet var textfield6:  UITextField!                       
     @IBOutlet var textfield7:  UITextField!                       
     @IBOutlet var textfield8:  UITextField!                       
     @IBOutlet var textfield9:  UITextField!                       
     @IBOutlet var textfield10: UITextField!                       
    
     override func viewDidLoad() {
         super.viewDidLoad()
         // Do any additional setup after loading the view, typically from a nib.
     }
    
     @IBAction func checkNumbers() {                       
         var numArray = [                                          
         Int(textfield1.text!)!,                           
         Int(textfield2.text!)!,
         Int(textfield3.text!)!,
         Int(textfield4.text!)!,
         Int(textfield5.text!)!,
         Int(textfield6.text!)!,
         Int(textfield7.text!)!,
 vInt(textfield8.text!)!,
         Int(textfield9.text!)!,
         Int(textfield10.text!)!
         ]
         for outerLoop in 0...numArray.count-2 {           
             for innerLoop in outerLoop...numArray.count-1 {
                 if numArray[outerLoop] > numArray[innerLoop] {
                     var temp = numArray[outerLoop]
                     numArray[outerLoop] = numArray[innerLoop]     
                     numArray[innerLoop] = temp
                 }
             }
         }
         textfield1.text = "\(numArray[0])"                
         textfield2.text = "\(numArray[1])"                        
         textfield3.text = "\(numArray[2])"                        
         textfield4.text = "\(numArray[3])"                        
         textfield5.text = "\(numArray[4])"                        
         textfield6.text = "\(numArray[5])"                        
         textfield7.text = "\(numArray[6])"                        
         textfield8.text = "\(numArray[7])"                        
         textfield9.text = "\(numArray[8])"                        
         textfield10.text = "\(numArray[9])"                       
    }
  
     override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()
         // Dispose of any resources that can be recreated.
     }
 }
  

❶  These IBOutlets allow us to get and set the text of the 10 TextFields, so that we can handle the numbers that the user enters

❷  This IBAction will use the “Selection Sort” to sort the numbers, and put the sorted text back into the TextFields.

❸  Using “Int()” we are able to convert the text from the textfields (as Strings) to Integers.

❹   This is a “Selection Sort” Algorithm with For Loop statements.

❺  This is where we set the text of all the textfields, with the sorted numbers.

Explanation of the Code, SELECTION SORTING!

We used an algorithm called the “Selection Sort” algorithm.

Let me explain it to you.

We’re running two loops, one inside of the other. We have an outer loop using the variable “outerLoop”, and an inner loop using the variable “innerLoop”. The outer loop goes through all the numbers, except the last one, once. Every time the outer loop repeats the inner loop loops though the remaining numbers and brings the least numbers up to the top by repeatedly swapping the outer loop’s number with the smaller numbers below it. This repeats, with the help of “outerLoop”, up to the one less than the end of the array, and we get a sorted array in ascending order!

Why do I need to know how to sort things?  How can I use this in my own programs?

Although built-in functions can sort your Array, it’s essential that you do this exercise yourself. It makes you familiar with coding techniques and problem solving.

If you want to know how you can use Sorting in your applications, it’s simple: wherever you need to check for duplicate items in arrays, you’ll use sorting; sorting also makes searching for values faster.

Again, I’m only listing a few examples, although sorting can be used in MANY more ways!

Go to the second dimension: Rows and Columns!

Now, I’ll be teaching you about the second dimension. This means that instead of only having rows, our array will have rows AND columns. You’ll get a “grid” or a “matrix”.

Let me show you a visual example of the arrays we’ll be creating:

Table 2 Tables showing the two dimensional arrays

teamArr array

scoresArr Array

player1

player2

player3

student1

student2

student3

student4

student5

team1

Ann

Bob

Tim

test1

1

3

5

2

4

team2

Todd

Jimmy

Tom

test2

1

6

2

2

6

team3

Frank

Amy

Maya

Now, let’s code it:

An array with rows and columns is called a two-dimensional array. You could also have three or four dimensional arrays, but that’d too complicated to explain now. In simple terms, a two-dimensional array is an array inside another array, like this:

  
 var teamsArr: [[String]] =
 [[“Ann”, “Bob”, “Tim”],
  [“Todd”, “Jimmy”, “Tom”],
  [“Frank”, “Amy”, “Maya”]]
  
 var scoresArr: [[Int]] = [[1, 3, 5, 2, 4], [1, 6, 2, 2, 6]]
 ...
  

As you can see, the declaration of the array changes to:

  
 [[<TYPE>]]
  

As opposed to:

  
 [<TYPE>]
  

The difference, if you can’t make out, is that this declaration has two pairs of square brackets around the type, not one pair. You could have as many brackets as you like. The more brackets you put, the more dimensions the array has. Next, in order to access your name “Amy” at row 3, and column 2 from teamsArr you’ll code like:

  
 print(teamArr[2][1])
  

NOTE Like the rest, the position for Amy is row index 2, and column index 1 because ranges always start with 0

Now you know what arrays are and how to use them. If you want to know more about coding with Swift, read the first chapter of Hello Swift! here and see this slide deck.