๐ŸŽ“ A1Learner
๐Ÿ”
0 of 36 lessons completed

Swift Collection Transformations

Collection transformations build a new shape from an existing collection. Zip, enumerated, and mapValues each reshape data in a different way.

Zip pairs two arrays

The names and scores line up by position in the two arrays. The loop prints one paired line per position.

let names = ["Ana", "Ben", "Cleo"]
let scores = [90, 75, 88]
for (name, score) in zip(names, scores) {
    print("\(name) \(score)")
}

Zip builds a dictionary

The zip pairs feed a dictionary keyed by name. The entries print over the sorted keys, with a fallback of zero for the lookup.

let names = ["Ana", "Ben", "Cleo"]
let scores = [90, 75, 88]
let table = Dictionary(uniqueKeysWithValues: zip(names, scores))
for key in table.keys.sorted() {
    print("\(key) \(table[key] ?? 0)")
}

Enumerated numbers the lines

Enumerated gives each step with its offset, starting from zero. Adding one to the offset prints line numbers that start from one.

let steps = ["Mix", "Bake", "Serve"]
for (offset, step) in steps.enumerated() {
    print("\(offset + 1). \(step)")
}

MapValues changes every value

MapValues doubles each price and leaves both keys in place. The new dictionary prints over the sorted keys.

let prices = ["pen": 2, "book": 5]
let doubled = prices.mapValues { $0 * 2 }
for key in doubled.keys.sorted() {
    print("\(key) \(doubled[key] ?? 0)")
}

Example

let names = ["Ana", "Ben", "Cleo"]
let scores = [90, 75, 88]
for (offset, pair) in zip(names, scores).enumerated() {
    print("\(offset + 1). \(pair.0) scored \(pair.1)")
}

Key points

  • Zip pairs elements from two sequences by position.
  • The pairing stops when the shorter sequence runs out.
  • A zip result can build a dictionary when the first sequence holds the keys.
  • Enumerated pairs each element with its offset.
  • Offsets start at zero, so adding one numbers lines from one.
  • MapValues changes each value in a dictionary and keeps every key.

In this example, zip first pairs each name with the score at the same position. Enumerated then pairs each of those pairs with an offset starting from zero. Adding one to the offset numbers the lines from one, and the pair members print the name and the score for each line.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Zip pairs a three element array with a two element array. How many pairs does the pairing make?