typestar

enumerated and zip in Swift

Walk with indices, or walk two sequences in lockstep.

let boats = ["Kestrel", "Sable", "Petrel"]
let times = [3612.0, 3599.5, 3688.0]

// enumerated pairs each element with its offset.
for (place, boat) in boats.enumerated() {
    print("\(place + 1). \(boat)")
}

// zip walks two sequences in lockstep.
for (boat, time) in zip(boats, times) {
    print("\(boat) finished in \(time) s")
}

let board = Dictionary(uniqueKeysWithValues: zip(boats, times))
print("Sable: \(board["Sable"] ?? 0) s")

How it works

  1. enumerated() pairs each element with its offset.
  2. zip(boats, times) stops at the shorter sequence.
  3. Dictionary(uniqueKeysWithValues:) turns the pairs into a map.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
433
Tokens
118
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 109 seconds.

Type this snippet

Step 2 of 3 in Collections, step 14 of 27 in Language basics.

← Previous Next →