Learn/Swift/7. Collections
Lesson 7 of 8
Sign in

Swift, lesson 7

Collections

One variable holds one value. To handle a whole shopping list, a season of game scores or a phone book, you need a collection. Swift's two workhorses are the array (an ordered list) and the dictionary (a lookup table from keys to values).

Arrays

An array keeps values of one type in order. Write it with square brackets:

The type [Int] reads "array of Int". As with single values, let makes the array fixed and var lets you change it.

Positions (indices) start at 0, so the last valid index is count - 1. Asking for an index outside that range crashes the program. When you are not sure an item exists, use the safe properties first and last, which return optionals ( for an empty array).

2 exercises to try what you just read.

Exercise 1

Season scores

Press Ctrl Enter or Check to test your code.

Exercise 2

Vote counter

Press Ctrl Enter or Check to test your code.

nil

Looping over an array gives you each item in order. Use enumerated() when you also want the position:

A few handy built-ins: contains(_:) checks whether a value is present, sorted() returns a sorted copy, and min() and max() return the smallest and largest item as optionals (an empty array has neither).

Splitting a line into an array

Input often puts several values on one line. split(separator:) cuts a string into pieces. Each piece can go straight into Int(...):

if let here unwraps the optional from Int(...): the block only runs when the conversion worked, and inside it n is a plain Int.

Dictionaries

A dictionary maps keys to values. Its type is written [Key: Value]:

Looking up a key gives an optional, because the key might not be there:

For counting, the default: form is perfect. It treats a missing key as the default value, so you can update it in one step:

Looping over a dictionary gives (key, value) pairs. A dictionary has no order, and the order you see can change between runs. When order matters, sort the keys first:

Swift also has Set, an unordered collection where each value appears at most once. It is great for "have I seen this before?" questions, and you will meet it again later.

Further reading

  • Collection Types
  • Control Flow: iterating over arrays and dictionaries

Read one line of game scores separated by single spaces (at least one score) and print a summary.

Output: four lines: Games: with the number of scores, Best: with the highest, Worst: with the lowest and Total: with their sum.

Sample input:

Sample output:

A class is voting for the name of its pet hamster. Each line of input is one vote: a single name. Count the votes and print each name with its number of votes, sorted alphabetically by name, in the form name: votes.

Input: zero or more lines, each with one name (no spaces). Names are case-sensitive.

Output: one line per distinct name, alphabetical. Print nothing when there are no votes.

Sample input:

Sample output:

var scores = [12, 40, 7]        // inferred as [Int]
var names: [String] = []        // an empty array needs its type spelled out
scores.append(25)        // [12, 40, 7, 25]
scores[0] = 15           // replace the first item
print(scores.count)      // 4
print(scores.isEmpty)    // false
print(scores[1])         // 40
let removed = scores.remove(at: 2)   // removes 7 and gives it back
for score in scores {
    print(score)
}
for (index, name) in ["Ann", "Bo"].enumerated() {
    print("\(index + 1). \(name)")   // 1. Ann, 2. Bo
}
let best = scores.max() ?? 0
let line = "3 14 15"
var numbers: [Int] = []
for piece in line.split(separator: " ") {
    if let n = Int(piece) {
        numbers.append(n)
    }
}
// numbers is [3, 14, 15]
var stock: [String: Int] = ["apples": 4, "pears": 0]
stock["plums"] = 9          // add a new pair
stock["apples"] = 5         // replace a value
stock["pears"] = nil        // remove a pair
let plums = stock["plums"] ?? 0     // 9
let kiwis = stock["kiwis"] ?? 0     // 0
var counts: [String: Int] = [:]
counts["cat", default: 0] += 1
for fruit in stock.keys.sorted() {
    print("\(fruit): \(stock[fruit] ?? 0)")
}
12 40 7 25
Games: 4
Best: 40
Worst: 7
Total: 84
Nibbles
Peanut
Nibbles
Biscuit
Biscuit: 1
Nibbles: 2
Peanut: 1