Chapter    9

Arrays and Dictionaries

Almost every program needs to accept data so it can manipulate that data and calculate a useful result. The simplest way to store data temporarily is through variables that can store numbers or text strings. However, what if you need to store multiple chunks of data such as a list of names or a list of product numbers? You could create multiple variables like this:

var employee001, employee002, employee003 : String

Unfortunately, creating separate variables to store related data can be clumsy. What if you don’t know how many items you need to store? Then you may create too many or not enough variables. Even worse, storing related data in separate variables means it’s easy to overlook the relationship between data.

For example, if you stored the names of three employees in three different variables, how do you know if there isn’t a fourth, fifth, or sixth variable containing additional employee names? Unless you keep variables together in your code, it’s easy to lose track of related data stored in separate variables.

That’s why Swift offers two additional ways to store data: arrays and dictionaries. The main idea behind both data structures is that you create a single variable that can hold multiple items. Now you can store related data in one location and easily find and retrieve it again.

Both arrays and dictionaries are designed to store multiple copies of the same data type such as a list of names (String) or a list of numbers (Int). If you wanted to store a list consisting of different data types such as integers, decimal numbers, and strings, you can declare the array or dictionary to hold AnyObject data types, which can store any type of data.

Using Arrays

You can think of an array as an endless series of buckets that can hold exactly one chunk of data. To help you find data stored in an array, each array element (bucket) is identified by a number called an index. The first item in an array is defined at index 0, the second item is defined at index 1, the third item is defined at index 2, and so on as shown in Figure 9-1.

9781484212349_Fig09-01.jpg

Figure 9-1. The structure of an array

To create an array, you must define the name of the array and the type of data the array can hold. One way to create an array is like this:

var arrayName = Array<DataType>()>()

The array name can be anything you wish, although it’s best to choose a descriptive name that identifies the type of data the array holds, such as employeeArray. The data type can be Int (integer), String (strings), Float or Double (decimal numbers), or even the name of another data structure. (It’s possible to have an array that holds other arrays.)

A second way to create an array is like this:

var arrayName = [DataType]()

Both of these methods create an empty array. At that point, you’ll need to start adding items into that array. If you want to create an array and store it with items at the same time, you’ll need to use the arrayLiteral keyword such as:

var arrayName = Array<Int>(arrayLiteral: 34, 89, 70, 1, -24)

or

var arrayName = [Int](arrayLiteral: 34, 89, 70, 1, -24)

Both of these commands create an array called “arrayName” that can only hold integers. Then the arrayLiteral keyword followed by the list of integers fills up the array with data. Since you have to define the data type, both of these methods will work with the AnyObject so you can store different types of data in an array.

A shorter and much simpler way to create an array is to define an array name and set it equal to a list of items of the same data type like this:

var myArrray = [34, 89, 70, 1, -24]

Swift then infers the data type of the array based on the data. This method only works if all items in the array are of the same data type such as all integers or all decimal numbers.

 Note  When you declare an array with the “var” keyword, you can add and delete items in that array. If you don’t want an array to change, declare it with the “let” keyword like this: let arrayName = [34, 89, 70, 1, -24]. An array declared with the “let” keyword can never be modified.

In the previous examples of arrays holding integers, the first number (34) is at index 0, the second number (89) is at index 1, the third number (70) is at index 2, the fourth number (1) is at index 3, and the fifth number (-24) is at index 4. Because arrays count the index numbers starting with 0, Swift arrays are known as zero-based arrays. (Some programming languages count the index of arrays starting with 1 so they’re called one-based arrays.)

Adding Items to an Array

Whether an array is empty or already filled with data, you can always add more items to an array by using the append command like this:

arrayName.append(data)

You must specify the array name to add data to and put the actual data in parentheses. Make sure the data you add is of the proper data type. So if you want to add data to an array that can only hold integers, you can only add another integer to that array.

Instead of using the append command, you can use the addition compound assignment operator to add items to the end of an array like this:

arrayName3 += [data1, data2, data3, ... dataN]

The += compound assignment operator can add multiple items to the end of an array while the append command only adds one item at a time to the end of an array.

The append command always adds new items to the end of an array. If you want to add a new item to a specific location in an array, you can use the insert and atIndex commands like this:

arrayName.insert(data, atIndex: index)

With the insert command, you must add data that’s the proper data type for that array. Then you must also specify the index number. If you choose an index number larger than the array size, the insert command won’t work.

To see how to create an array and add data to it, create a new playground by following these steps:

  1. Start Xcode.
  2. Choose File image New image Playground. (If you see the Xcode welcome screen, you can also click on Get started with a playground.) Xcode asks for a playground name and platform.
  3. Click in the Name text field and type ArrayPlayground.
  4. Click in the Platform pop-up menu and choose OS X. Xcode asks where you want to save your playground file.
  5. Click on a folder where you want to save your playground file and click the Create button. Xcode displays the playground file.
  6. Edit the code as follows:
    import Cocoa

    var arrayName = Array<Int>(arrayLiteral: 34, 89, 70, 1, -24)

    var arrayName2 = [Int](arrayLiteral: 34, 89, 70, 1, -24)

    arrayName.append(2)
    arrayName2.append(2)

    arrayName.insert(-37, atIndex: 2)
    arrayName2.insert(-37, atIndex: 2)

Notice how the append and insert commands work differently as shown in Figure 9-2.

9781484212349_Fig09-02.jpg

Figure 9-2. Creating arrays in a playground

Deleting Items From an Array

Just as you can add items to an array, so can you also delete items from an array. To remove the last item in an array, you can use the removeLast command like this:

arrayName.removeLast()

Not only will this delete the last item in an array, but it will also return that value. If you want to save the last item of an array in a variable, you could do something like this:

var item = arrayName.removeLast()

If you want to remove a specific item from an array, you can identify the index number of that item with the removeAtIndex command like this:

arrayName.removeAtIndex(number)

So if you wanted to remove the second item in an array, you would specify an index of 1. Like the removeLast command, the removeAtIndex command also returns a value that you could store in a variable like this:

var item = arrayName.removeAtIndex(1)

If you wanted to remove all items from an array, you can use the removeAll command like this:

arrayName.removeAll()

To see how to delete items from an array, follow these steps:

  1. Make sure the ArrayPlayground file is loaded in Xcode.
  2. Edit the code as follows:
    import Cocoa

    var arrayName = [Int](arrayLiteral: 3, 8, 9, 21)
    var item = arrayName.removeLast()
    print (arrayName)
    print (item)

    item = arrayName.removeAtIndex(1)
    print (arrayName)
    print (item)

    arrayName.removeAll()

Notice how the different commands work when deleting items from an array as shown in Figure 9-3. When specifying index values, you must make sure your index number exists. That means if an array consists of three items, the first item is at index 0, the second is at index 1, and the third is at index 2. So you can remove an item from this array at index values 0, 1, or 2, but any other index number will not work.

9781484212349_Fig09-03.jpg

Figure 9-3. Deleting items from an array

Deleting items from an array physically removes that item from that array. Rather than delete an item from an array, you can also replace an existing item with a new value. All you have to do is specify the index value of the array item you want to replace and assign new data to it like this:

arrayName[index] = newData

So if you wanted to replace the second item in an array (at index value 1) with new data, you could do the following:

arrayName[1] = 91

Whatever existing value was stored in the array at index value 1 gets replaced with the number 91. When replacing data, the new data must be of the same data type as the rest of the items in the array such as integers or strings.

Querying Arrays

When you have an array, you might want to know if the array is empty (has zero items stored in it), or if the array does have items, how many items it contains. To determine if an array is empty or not, you can use the isEmpty command that returns a Boolean value like this:

arrayName.isEmpty

If you want to store this Boolean value in a variable, you could do this:

var flag = arrayName.isEmpty

If you want to know how many items are stored in an array, you can use the count command like this:

arrayName.count

If you want to store this integer value in a variable, you could do this:

var total = arrayName.count

If you just want to access an individual array item, you can copy it from an array and store its value in a variable like this:

var item = arrayName[index]

This lets you retrieve an item out of an array from a specific index location and store that value in a variable. When retrieving data from an array, make sure you specify a valid index value. So if the array contains three items, the index values would be 0, 1, and 2. That means if you wanted to retrieve the second item in an array (at index 1), you could use this code:

var item = arrayName[1]

Manipulating Arrays

Two common ways to manipulate an array is to reverse the order of all the items or rearrange the items in ascending or descending order. This simply reverses the order of all items in an array without regard to their actual values such as:

arrayName.reverse()

When you sort an array in ascending order, the lowest value gets stored in the first item of the array, and the highest value gets stored in the last item of the array. When you sort strings, Swift sorts them in alphabetical order. To sort an array in ascending order, you have two choices:

myArray.sort { $0 < $1 }
or
myArray.sort ()

When you sort an array in descending order, the highest value gets stored in the first item of the array, and the lowest value gets stored in the last item of the array. When you sort strings, Swift sorts them in reverse alphabetical order. To sort an array in descending order, use this:

myArray.sort { $1 < $0 }

To see how sorting an array works, follow these steps:

  1. Make sure the ArrayPlayground file is loaded in Xcode.
  2. Edit the code as follows:
    import Cocoa

    var myArray = ["Bob", "Fred", "Jane", "Mary"]

    print (myArray.sort())

    var sortedArray = myArray.sort() { $1 < $0 }
    print (sortedArray)

Notice that sorting an array changes the position of items based on their content as shown in Figure 9-4.

9781484212349_Fig09-04.jpg

Figure 9-4. Sorting an array

Using Dictionaries

Arrays can be useful for storing lists of related data. The biggest drawback with an array comes when you want to retrieve specific data. Unless you know the exact index number of an item in an array, retrieving data can be cumbersome.

That’s the advantage of a dictionary. Unlike an array that just stores data, a dictionary stores two chunks of data known as a key-value pair. The value represents the data you want to save, and the key represents a quick way to retrieve your data.

For example, consider a list of phone numbers. If you stored phone numbers in an array, you would have to retrieve a specific phone number by knowing its exact index value. However, if you stored phone numbers in a dictionary, you could store each phone number (value) with a name (key). Now if you wanted to retrieve a particular phone number, you just search for the key (the person’s name).

Regardless of where that data might be stored in the dictionary, you can quickly retrieve a value using a key. That makes retrieving data from a dictionary far easier than retrieving similar data from an array.

Think of a dictionary like an array but instead of storing one chunk of data, you’re storing a pair of data (a key and a value). Both the key and the value can be of different data types, but all the keys must be of the same data type and all the values in a dictionary must be of the same data type. However, keys and values can be of different data types. For example, the keys of a dictionary could be of String data types while the values could be Int data types.

To create a dictionary, you must define the dictionary and the data types for both the key and its associated value. One way to define a dictionary is to do this:

var DictionaryName = [keyDataType: valueDatatype]()

A second way to define a dictionary is to create a list of key:value pairs like this:

var DictionaryName = [102: "Fred", 87: "Valerie"]

When you directly assign key:value pairs, Swift infers the data type of the key and the value. In this case, the key data type is an integer (Int) and the value data type is a string (String).

Adding Items to a Dictionary

Whether a dictionary is empty or already filled with data, you can always add more items to a dictionary by specifying the dictionary name and its key value, and then assigning a value such as:

DictionaryName [key] = value

To see how to create a dictionary and add data to it, create a new playground by following these steps:

  1. Start Xcode.
  2. Choose File image New image Playground. (If you see the Xcode welcome screen, you can also click on Get started with a playground.) Xcode asks for a playground name and platform.
  3. Click in the Name text field and type DictionaryPlayground.
  4. Click in the Platform pop-up menu and choose OS X. Xcode asks where you want to save your playground file.
  5. Click on a folder where you want to save your playground file and click the Create button. Xcode displays the playground file.
  6. Edit the code as follows:
    import Cocoa

    var DictionaryName = [102: "Fred", 87: "Valerie"]

    DictionaryName [120] = "John"
    DictionaryName [96] = "Jane"

    print (DictionaryName)

This Swift code defines a dictionary where the key:value data types are Int:String, which Swift infers from the type of data initially stored in the dictionary.

The next two lines define a key (120) and a value (“John”), which gets stored in the dictionary. Then the other line defines a key (96) and a value (“Jane”), which also gets stored in the dictionary. The last print command lets you see how the dictionary has changed as shown in Figure 9-5.

9781484212349_Fig09-05.jpg

Figure 9-5. Creating a dictionary and adding new key:value data to it

Retrieving and Updating Data in a Dictionary

Once a dictionary contains key:value pairs, you can retrieve the value by using the key. To do that, you specify the dictionary name and a key. Then you assign this value to a variable such as:

variable = DictionaryName [key]!

The variable must be the same data type as the value stored in the dictionary. Also notice the exclamation mark, which defines an implicitly unwrapped variable. This exclamation mark ensures that if the key doesn’t exist in the dictionary, the nonexistent value does not crash your program.

The following example defines two key:value pairs of data in a dictionary. Then it uses the 87 key to retrieve the value from the dictionary, which is the string “Valeria” as shown in Figure 9-6:

var DictionaryName = [102: "Fred", 87: "Valerie"]
var name : String
name = DictionaryName [87]!
print (name)

9781484212349_Fig09-06.jpg

Figure 9-6. Retrieving a value with a key and updating an existing key with new data

Once you’ve stored a key:value pair in a dictionary, you can always assign a new value to an existing key using the updateValue command like this:

DictionaryName.updateValue(value, forKey: key)

So if you wanted to update the value stored with the 87 key, you could do the following:

DictionaryName.updateValue("Sam", forKey: 87)

To see how to retrieve a value from a dictionary using a key and then update a value for an existing key, follow these steps:

  1. Make sure the LoopingPlayground file is loaded in Xcode.
  2. Edit the code as follows:
    import Cocoa

    var DictionaryName = [102: "Fred", 87: "Valerie"]

    DictionaryName [120] = "John"
    DictionaryName [96] = "Jane"
    print (DictionaryName)

    var name : String
    name = DictionaryName [87]!
    print (name)

    DictionaryName.updateValue("Sam", forKey: 87)
    name = DictionaryName [87]!
    print (name)

Notice that the first time the dictionary retrieves the value associated with the 87 key, it returns the string “Valerie.” Then the updateValue command replaces “Valerie” with “Sam” so the next time the dictionary retrieves the value associated with the 87 key, it returns the string “Sam” (see Figure 9-6).

Deleting Data in a Dictionary

Once a dictionary contains key:value pairs, you can delete the value associated with a specific key by using the removeValueForKey command like this:

DictionaryName.removeValueForKey(key)

The removeValueForKey command removes both the key and the value associated with that key. Note that if you specify a key that doesn’t exist in the dictionary, the removeValueForKey command does nothing.

If you want to delete all the key:value pairs in a dictionary, you can just use the removeAll command like this:

DictionaryName.removeAll()

Querying a Dictionary

Once you store key:value pairs in a dictionary, you can use the following commands to get information about a dictionary:

  • count – counts the number of key:value pairs stored in a dictionary
  • keys – retrieves a list of all the keys stored in a dictionary
  • values – retrieves a list of all the values stored in a dictionary

The count command only needs the dictionary name and returns an integer value that you can assign to a variable such as:

var name = DictionaryName.count

The keys and values commands need a dictionary name and returns a list of items that you can store in an array such as:

let myKeys = Array(DictionaryName.keys)

To see how to count and retrieve keys and values from a dictionary, follow these steps:

  1. Make sure the DictionaryPlayground file is loaded in Xcode.
  2. Edit the code as follows:
    import Cocoa

    var myDictionary = [12: "Joe", 7: "Walter"]

    myDictionary.removeValueForKey(7)
    print (myDictionary)

    myDictionary.removeAll()
    print (myDictionary)

    myDictionary = [25: "Stephanie", 98: "Nancy"]

    print (myDictionary.count)
    let myKeys = Array(myDictionary.keys)
    let myValues = Array(myDictionary.values)

Notice how the removeValueForKey command removes an existing key:value pair while the removeAll command empties the entire dictionary. Also notice how the count command counts all key:value pairs while the keys and values commands return a list of the keys and values respectively as shown in Figure 9-7.

9781484212349_Fig09-07.jpg

Figure 9-7. Deleting dictionary data, counting, and retrieving keys and values

Using Dictionaries in an OS X Program

In this sample program, the computer creates a list of data stored in a dictionary. Then through the user interface, the user can add new data to the dictionary, delete existing data, or get information about the dictionary.

Create a new OS X project by following these steps:

  1. From within Xcode choose File image New image Project.
  2. Click Application under the OS X category.
  3. Click Cocoa Application and click the Next button. Xcode now asks for a product name.
  4. Click in the Product Name text field and type DictionaryProgram.
  5. Make sure the Language pop-up menu displays Swift and that no check boxes are selected.
  6. Click the Next button. Xcode asks where you want to store the project.
  7. Choose a folder to store your project and click the Create button.
  8. Click the MainMenu.xib file in the Project Navigator.
  9. Click on the DictionaryProgram icon to make the window of the user interface appear.
  10. Choose View image Utilities image Show Object Library to make the Object Library appear in the bottom right corner of the Xcode window.
  11. Drag three Push Buttons, six Labels, and six Text Fields on the user interface and double-click on the push buttons and labels to change the text that appears on them so that it looks similar to Figure 9-8.

9781484212349_Fig09-08.jpg

Figure 9-8. The user interface of the DictionaryProgram

The Add button will let you type in a key and value in the text fields on the right. The Delete button will let you specify a key to delete its associated value from a dictionary. The Query button will display the total number of items along with the list of keys and values currently stored in the dictionary.

Each text field will need a separate IBOutlet and each push button will need a separate IBAction method, which you’ll need to create by Control-dragging each item from the user interface to your AppDelegate.swift file:

  1. With your user interface still visible in the Xcode window, choose View image Assistant Editor image Show Assistant Editor. The AppDelegate.swift file appears next to the user interface.
  2. Move the mouse over the Add button, hold down the Control key, and drag just above the last curly bracket at the bottom of the AppDelegate.swift file.
  3. Release the mouse and the Control key. A pop-up window appears.
  4. Click in the Connection pop-up menu and choose Action.
  5. Click in the Name text field and type addButton.
  6. Click in the Type pop-up menu and choose NSButton. Then click the Connect button.
  7. Move the mouse over the Delete button, hold down the Control key, and drag just above the last curly bracket at the bottom of the AppDelegate.swift file.
  8. Release the mouse and the Control key. A pop-up window appears.
  9. Click in the Connection pop-up menu and choose Action.
  10. Click in the Name text field and type deleteButton.
  11. Click in the Type pop-up menu and choose NSButton. Then click the Connect button.
  12. Move the mouse over the Query button, hold down the Control key, and drag just above the last curly bracket at the bottom of the AppDelegate.swift file.
  13. Release the mouse and the Control key. A pop-up window appears.
  14. Click in the Connection pop-up menu and choose Action.
  15. Click in the Name text field and type queryButton.
  16. Click in the Type pop-up menu and choose NSButton. Then click the Connect button. The bottom of the AppDelegate.swift file should look like this:
    @IBAction func addButton(sender: NSButton) {
    }

    @IBAction func deleteButton(sender: NSButton) {
    }

    @IBAction func queryButton(sender: NSButton) {
    }
  17. Move the mouse over the Key text field that appears to the right of the Add button, hold down the Control key, and drag below the @IBOutlet line in the AppDelegate.swift file.
  18. Release the mouse and the Control key. A pop-up window appears.
  19. Click in the Name text field and type addKeyField and click the Connect button.
  20. Move the mouse over the Value text field that appears to the right of the Add button, hold down the Control key, and drag below the @IBOutlet line in the AppDelegate.swift file.
  21. Release the mouse and the Control key. A pop-up window appears.
  22. Click in the Name text field and type addValueField and click the Connect button.
  23. Move the mouse over the Key text field that appears to the right of the Delete button, hold down the Control key, and drag below the @IBOutlet line in the AppDelegate.swift file.
  24. Release the mouse and the Control key. A pop-up window appears.
  25. Click in the Name text field and type deleteKeyField and click the Connect button.
  26. Move the mouse over the Count text field that appears to the right of the Query button, hold down the Control key, and drag below the @IBOutlet line in the AppDelegate.swift file.
  27. Release the mouse and the Control key. A pop-up window appears.
  28. Click in the Name text field and type queryCountField and click the Connect button.
  29. Move the mouse over the Keys text field that appears to the right of the Query button, hold down the Control key, and drag below the @IBOutlet line in the AppDelegate.swift file.
  30. Release the mouse and the Control key. A pop-up window appears.
  31. Click in the Name text field and type queryKeysField and click the Connect button.
  32. Move the mouse over the Values text field that appears to the right of the Query button, hold down the Control key, and drag below the @IBOutlet line in the AppDelegate.swift file.
  33. Release the mouse and the Control key. A pop-up window appears.
  34. Click in the Name text field and type queryValuesField and click the Connect button.
  35. You should now have the following IBOutlets that represent all the text fields on your user interface:
    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var addKeyField: NSTextField!
    @IBOutlet weak var addValueField: NSTextField!
    @IBOutlet weak var deleteKeyField: NSTextField!
    @IBOutlet weak var queryCountField: NSTextField!
    @IBOutlet weak var queryKeysField: NSTextField!
    @IBOutlet weak var queryValuesField: NSTextField!

At this point we’ve connected the user interface to our Swift code so we can use the IBOutlets to retrieve and display data on the user interface. We’ve also created the IBAction methods so the push buttons on the user interface will make the program actually work. Now we just need to write Swift code to create an initial dictionary and then write more Swift code in each IBAction method to add, delete, or query the dictionary.

  1. Underneath the IBOutlet list in the AppDelegate.swift file, type the following to create a dictionary where the keys are integers and the values are strings:
    var myDictionary = [1:"Joe", 2:"Cindy", 3:"Frank"]
  2. Modify the addButton IBAction method so it takes a value from the Key and Value text fields and adds them to the dictionary as follows:
    @IBAction func addButton(sender: NSButton) {
        myDictionary.updateValue(addValueField.stringValue, forKey: addKeyField.integerValue)
    }
  3. Modify the deleteButton IBAction method so it takes a value from the Key text field and deletes the associates value from the dictionary as follows:
    @IBAction func deleteButton(sender: NSButton) {
        myDictionary.removeValueForKey(deleteKeyField.integerValue)
    }
  4. Modify the queryButton IBAction method as follows:
    @IBAction func queryButton(sender: NSButton) {
        queryCountField.integerValue = myDictionary.count

        var keyList = ""

        for key in myDictionary.keys {
            keyList = keyList + "(key)" + " "
        }
        queryKeysField.stringValue = keyList

        var valueList = ""
        for value in myDictionary.values {
            valueList = valueList + "(value)" + " "
        }
        queryValuesField.stringValue = valueList

    }

The myDictionary.count command simply counts the number of key:value pairs in the dictionary and displays that number in the queryCountField IBOutlet.

The first for-in loop goes through each key in the dictionary and stores it in a string called keyList. Then it displays this text string in the queryKeysField IBOutlet.

The last for loop goes through each value in the dictionary and stores it in a string called valueList. Then it displays this text string in the queryValuesField IBOutlet.

The complete contents of the AppDelegate.swift file should look like this:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var addKeyField: NSTextField!
    @IBOutlet weak var addValueField: NSTextField!
    @IBOutlet weak var deleteKeyField: NSTextField!
    @IBOutlet weak var queryCountField: NSTextField!
    @IBOutlet weak var queryKeysField: NSTextField!
    @IBOutlet weak var queryValuesField: NSTextField!

    var myDictionary = [1:"Joe", 2:"Cindy", 3:"Frank"]

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }

    @IBAction func addButton(sender: NSButton) {
        myDictionary.updateValue(addValueField.stringValue, forKey: addKeyField.integerValue)
    }

    @IBAction func deleteButton(sender: NSButton) {
        myDictionary.removeValueForKey(deleteKeyField.integerValue)
    }

    @IBAction func queryButton(sender: NSButton) {
        queryCountField.integerValue = myDictionary.count

        var keyList = ""

        for key in myDictionary.keys {
            keyList = keyList + "(key)" + " "
        }
        queryKeysField.stringValue = keyList

        var valueList = ""
        for value in myDictionary.values {
            valueList = valueList + "(value)" + " "
        }
        queryValuesField.stringValue = valueList

    }
}

The Query button works by just clicking on it to display information about the current dictionary contents.

The Add button works by the user typing in a key (integer) and a name (string) into the Key and Value text fields, then clicking the Add button.

The Delete button works by the user typing in a key (integer) and then clicking the Delete button.

After clicking either the Add or Delete button, click the Query button again to see your changes. To see how this program works, follow these steps:

  1. Choose Product image Run. Xcode runs your DictionaryProgram project.
  2. Click the Query button. The program shows the number of items in then dictionary (3), the list of keys (the numbers 1, 2, and 3), and the list of values (“Joe,” “Cindy,” and “Frank”). Don’t worry about the order of the keys and values. The important point is to see that the order of each key matches up with the correct value such as 1 for “Joe,” 2 for “Cindy,” and 3 for “Frank.”
  3. Type 3 in the Key field to the right of the Delete push button and then click the Delete button.
  4. Click the Query button. Notice that now the dictionary only contains two items: the keys 1 and 2, and the values “Joe” and “Cindy” as shown in Figure 9-9.

    9781484212349_Fig09-09.jpg

    Figure 9-9. Displaying the results after deleting a key:value pair

  5. Click in the Key text field to the right of the Add button and type 5.
  6. Click in the Value text field to the right of the Add button and type Felicia.
  7. Click the Add button.
  8. Click the Query button. Notice that the count is now 3 again; the keys are 1, 2 and 5; and the values are “Joe,” “Cindy,” and “Felicia.”
  9. Choose DictionaryProgram image Quit DictionaryProgram.

Summary

Arrays and dictionaries are two ways to store lists of related data in a single variable. Arrays make it easy to store data, but retrieving data can be cumbersome since you have to know the exact index value of the data you want to retrieve.

Dictionaries force you to store data with a key, but that key makes it easy to retrieve that data later without knowing the exact location it may be stored in the dictionary.

In the sample OS X program that you created, you also learned how for-in loops can count automatically through a dictionary. By now you should also be getting more comfortable creating user interfaces and seeing which items need IBOutlets and which items need IBAction methods.

Designing programs can occur in three distinct steps. First, create the user interface and customize it. Second, connect your user interface to your Swift file. Third, write Swift code to make your IBAction methods work.

Think of arrays and dictionaries as super variables that can store multiple data in a single variable name. If you only need to save a single value, then use a variable. If you need to store lists of related data, then use an array or a dictionary.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset