Swift, lesson 7
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).
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.
nilLooping 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).
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.
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.
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 outscores.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 backfor score in scores {
print(score)
}
for (index, name) in ["Ann", "Bo"].enumerated() {
print("\(index + 1). \(name)") // 1. Ann, 2. Bo
}let best = scores.max() ?? 0let 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 pairlet plums = stock["plums"] ?? 0 // 9
let kiwis = stock["kiwis"] ?? 0 // 0var counts: [String: Int] = [:]
counts["cat", default: 0] += 1for fruit in stock.keys.sorted() {
print("\(fruit): \(stock[fruit] ?? 0)")
}12 40 7 25Games: 4
Best: 40
Worst: 7
Total: 84Nibbles
Peanut
Nibbles
BiscuitBiscuit: 1
Nibbles: 2
Peanut: 1