AnyCompiler

Arrays and Dictionaries

An Array holds an ordered list of values of a single type, and grows and shrinks as needed when declared with var. for-in iterates over any array directly, with no index variable needed.

Dictionary

A Dictionary stores key-value pairs — indexing with [key] both inserts and retrieves. Reading a key that might not exist returns an optional, which is why reading ages["Alice"] below needs the ! to force-unwrap it once you're sure the key is there.

let numbers = [4, 8, 15, 16, 23]
var sum = 0
for n in numbers {
    sum += n
}
print(sum)

var ages: [String: Int] = [:]
ages["Alice"] = 30
ages["Bob"] = 25
print(ages["Alice"]!)
Output
66
30

Next: strings — a closer look at string interpolation and common string methods.

Practice exercise

Given let numbers = [4, 8, 15, 16], use a for-in loop to add up all the elements into a var sum starting at 0, then print sum.