Collections
The for loop in chapter 3 walked numbers in a range. It can also walk
values you chose and kept together. An array holds them in order:
let supplies = ["tea", "milk"]
print("First: \(supplies[0])")
print("Count: \(supplies.count)")
for item in supplies {
print("Pack \(item)")
}
First: tea
Count: 2
Pack tea
Pack milk
The first supply is at index 0, not 1. supplies.count tells you how
many there are, while for item in supplies visits them in their stored
order. Both entries are text, so Hirundo infers [String]: an array of
strings. You could write that type beside the name, but this literal already
makes the choice clear.
Two arrays from one
let keeps an array as it is: you cannot append to it or replace one of its
entries. Use var for an array you intend to change:
var supplies: [String] = ["tea", "milk"]
let saved = supplies
supplies.append("bread")
print("Saved count: \(saved.count)")
print("Current count: \(supplies.count)")
print("New last item: \(supplies[2])")
Saved count: 2
Current count: 3
New last item: bread
The annotation [String] says what the array holds; inference would work
here too. saved has two supplies even after supplies gains a third.
Changing one collection does not change the other. Hirundo need not make a
physical copy of all the storage the instant you write let saved = supplies;
it only has to keep that visible result true. Try appending another supply
and checking saved.count again.
Dictionaries come later, when we have a way to talk about a missing key.