Collection Types: Arrays & Dictionaries

Free iOS Development Tutorial

Get started on iOS Development with this comprehensive tutorial that covers topics including declaring and accessing arrays and dictionaries, mutable arrays and creating arrays without initial values.

This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Topics Covered in This IOS Development Tutorial:

Declaring Arrays & Accessing Their Indexes, Working with Mutable Arrays, Creating an Array Without an Initial Value, Declaring, Accessing, & Modifying Dictionaries, Creating a Dictionary Without an Initial Value

Exercise Overview

You’ve already seen how useful constants and variables are for storing data, but they only store a single value. If you want to store collections of data such as a to-do list or a directory of employees, you’ll need to use collection types. In this exercise, you’ll learn how to use two types of collections: arrays and dictionaries.

Getting Started

  1. Launch Xcode if it isn’t already open.

  2. Go to File > New > Playground.

  3. Under iOS, double–click on Blank.

  4. Navigate into Desktop > Class Files > yourname-iOS App Dev 1 Class.

  5. Save the file as: Collection Types.playground

  6. Click Create.

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Declaring Arrays & Accessing Their Indexes

The first collection type we’ll look at are arrays. An array stores an ordered list of information. Each item is referred to by its index, or numbered position in the array. It’s important to note that arrays are zero-indexed, which means the first item in the list has an index of zero (0), the second item is one (1), and so forth.

Knowing how to use arrays is essential for programmers because they are the basis of how data is organized on many levels. For example, the information that makes up a playlist in iTunes is stored in an array. Many user interfaces will access the data stored in an array’s indexes.

  1. To write an array you start the same as if you were declaring a constant or variable. The only difference is that the assigned value is written with square brackets [] containing comma-separated items. Replace the var str line with the bold comment and array that stores the numbered levels of our game:

    // ARRAYS
    let levels = [1,2, 3,4, 5]
  2. In order to access an item in an array, you type the name of the array, followed by brackets that contain the index number of the item you want. To access the first (0) index in the array, add the bold code:

    let levels = [1,2, 3,4, 5]
    levels[0]
  3. Notice on the right, in the Playground results sidebar, it prints: 1

    Remember that index 0 stores the first item in the array. So in this case, 0 (the first index) has the item called 1.

  4. Type the bold code to access the item stored in the array’s fifth (4) index:

    let levels = [1,2, 3,4, 5]
    levels[0]
    levels[4]
  5. Notice on the right, in the Playground results sidebar, it prints: 5

  6. Let’s put these levels into a sentence. Type the following bold print function:

    levels[4]
    print("This game is made up of \(levels[4]) levels")
  7. In the Playground results sidebar, notice it prints: This game is made up of 5 levels

  8. In real-world programming, we often don’t know how many indexes there are in an array. This is where Swift’s count property comes in handy. It counts how many indexes there are in the array. Edit the print function as shown in bold:

    print("This game is made up of \(levels.count) levels")

    You’ll see the same output in the sidebar.

Working with Mutable Arrays

Arrays can be stored in either constants or variables. We aren’t planning on adding more levels to our game, so we used a constant when we declared the previous array. However, when you intend to add, remove, or modify data in an array, you should use a variable to make it mutable (changeable).

  1. Let’s create a mutable array listing the players of our game, as this info is likely to change. Declare the array using a variable, as shown in bold below:

    print("This game is made up of \(levels.count) levels")
    
    var currentPlayers = ["John", "Steve", "Laurie", "Holly", "Sam"]
  2. Notice on the right, in the results sidebar, it prints all the names you just typed.

  3. Let’s see how we can pass in a new value to a mutable array. Add another player who just joined the game to the array using Swift’s pre-defined append method:

    var currentPlayers = ["John", "Steve", "Laurie", "Holly", "Sam"]
    currentPlayers.append("Max")

    NOTE: Methods are similar to functions, but they are associated with a type (such as an array). You’ll learn more about methods in later exercises.

  4. Notice in the results sidebar it prints all the previous names, and Max has been added at the end. The append method always adds the new value to the end of an array.

  5. Steve just got kicked out of the game, so we need to remove him. You can use another pre-defined method to remove array items at a particular index. Type:

    var currentPlayers = ["John", "Steve", "Laurie", "Holly", "Sam"]
    currentPlayers.append("Max")
    currentPlayers.remove(at: 1)

    Inside the remove method’s parentheses, the built-in at parameter is asking for an index (position) in the array as an argument. This index number is the one we want to remove. Remember, arrays are zero-indexed so John is at index 0 and Steve is at index 1.

  6. To see the current contents of an array, all we need to do is type the name of the array. Type the bold code to see what’s inside:

    var currentPlayers = ["John", "Steve", "Laurie", "Holly", "Sam"]
    currentPlayers.append("Max")
    currentPlayers.remove(at: 1)
    currentPlayers
  7. In the results sidebar, notice it prints all the players minus Steve. Notice also that there is no blank space in the list where Steve was because all the following players moved over. Laurie is now at index 1 in the array.

  8. Let’s say you want to add a new player but you don’t want him to go at the end of the list (like it would if you use the append method). Instead you want to add him between Laurie and Holly. Type the bold code:

    var currentPlayers = ["John", "Steve", "Laurie", "Holly", "Sam"]
    currentPlayers.append("Max")
    currentPlayers.remove(at: 1)
    currentPlayers
    currentPlayers.insert("Omar", at: 2)
  9. You should see the results sidebar print: ["John", "Laurie", "Omar", "Holly", "Sam", "Max"]

    NOTE: Everything inside an array must be of the same type (all strings, all integers, etc.). You can’t mix types in Swift—this goes back to type inference.

Creating an Array Without an Initial Value

In some cases, you may want to create an array that doesn’t have any initially assigned values. For example, let’s declare an array that will eventually hold high scores from the game. Currently, however, we don’t have any scores logged.

  1. Create an array for high scores (which we know will have integer values). Type the following to create an array called highScores with a data type of Int (integer):

    currentPlayers.insert("Omar", at: 2)
    
    var highScores = [Int]()

    Because you don’t have any values for Swift to infer the data type from, you need to define the array’s type. The parentheses () are needed to initialize (create) an array that is initially empty.

  2. A high score just came in. To add it, we can use the append method. Type:

    var highScores = [Int]()
    highScores.append(148)

    Now the highScores array has a single value in it.

Declaring, Accessing, & Modifying Dictionaries

Dictionaries are unordered lists of data whose values can be referenced by the keys associated with them. This is unlike an array, which is an ordered list that is referenced by index numbers and the placement of items in the array. Think of it like a regular dictionary, where you look up definitions (values) by searching for a particular word (key).

  1. At the bottom of the file, add a comment to make a visually separate section in our code and declare a dictionary:

    highScores.append(148)
    
    // DICTIONARIES
    var playerAttributes = ["name": "John", "city": "Brooklyn", "state": "New York", "username": "johnnyboy"]

Similar to an array, you use square brackets to declare a dictionary (because square brackets are for collection types). Inside the brackets, a dictionary contains key-value pairs. Note the colon used between the key and the corresponding value, and the commas separating each pair.

  1. Values in a dictionary are accessed in a similar manner to arrays such as: nameOfDictionary["nameOfKey"]. Type the bold code to access the name key:

    // DICTIONARIES
    var playerAttributes = ["name": "John", "city": "Brooklyn", "state": "New York", "username": "johnnyboy"]
    playerAttributes["name"]

    In the results sidebar, you should see John print out.

  2. Try accessing another value. Type:

    // DICTIONARIES
    var playerAttributes = ["name": "John", "city": "Brooklyn", "state": "New York", "username": "johnnyboy"]
    playerAttributes["name"]
    playerAttributes["city"]

    Brooklyn should print on the right.

  3. Next you’ll update a value using the updateValue method. John decided to give us his full name. Type:

    playerAttributes["name"]
    playerAttributes["city"]
    
    playerAttributes.updateValue("John Jones", forKey: "name")
  4. Notice that John prints out directly to the right of the line you just added. To make sure we didn’t get an error, try grabbing his updated name by typing:

    playerAttributes.updateValue("John Jones", forKey: "name")
    playerAttributes["name"]

    Phew, John Jones should print on the right. When updating a value in a dictionary, Swift Playgrounds show the old value instead of the new one to show you which old value got updated.

  5. What if John wanted to remain anonymous? Remove his name from the dictionary with the pre-defined removeValue method by typing:

    playerAttributes.updateValue("John Jones", forKey: "name")
    playerAttributes["name"]
    
    playerAttributes.removeValue(forKey: "name")
  6. Make sure his name has been removed. Type:

    playerAttributes.removeValue(forKey: "name")
    playerAttributes

    On the right, you should see the city, state, and username, but not the name. Remember that you can expand the sidebar on the right (by dragging the resize handle splitter) if you can’t see all this output.

  7. What about adding a new key-value pair? Easy! Add John’s phone number:

    playerAttributes.removeValue(forKey: "name")
    playerAttributes
    playerAttributes["phone"] = "212-765-4321"
  8. Check out the dictionary’s entire contents by typing playerAttributes at the bottom of the file.

Creating a Dictionary Without an Initial Value

  1. As with an array, you can initialize an empty dictionary and add values later. Type:

    playerAttributes["phone"] = "212-765-4321"
    playerAttributes
    
    var playerPref = [String: String]()

    The way that this works is:

    var nameOfDictionary = [keyType: valueType]()
  2. Add a key-value pair as follows:

    var playerPref = [String: String]()
    playerPref["speed"] = "fast"

    In this case, the key is speed and the value is fast.

  3. Check out the entire contents of the dictionary (one key-value pair) by typing playerPref at the bottom.

    NOTE: If you have time, feel free to add more key-value pairs such as one for difficulty (easy, medium, hard, etc.). Feel free to use the count property as well, as you can also use it with dictionaries.

  4. Save and close the file. Keep Xcode open, as we’ll use it in the next exercise.

Noble Desktop Publishing Team

The Noble Desktop Publishing Team includes writers, editors, instructors, and industry experts who collaborate to publish up-to-date content on today's top skills and software. From career guides to software tutorials to introductory video courses, Noble aims to produce relevant learning resources for people interested in coding, design, data, marketing, and other in-demand professions.

More articles by Noble Desktop Publishing Team

How to Learn IOS & Web Development

Master IOS Development, Web Development, Coding, and More with Hands-on Training. IOS Development Involves Designing Apps for Apple Mobile Devices with Tools Like Xcode and SwiftUI.

Yelp Facebook LinkedIn YouTube Twitter Instagram