Recall & Review
beginner
What does the
zip function do in Swift?It combines two sequences into a single sequence of pairs, where each pair contains one element from each sequence at the same position.
Click to reveal answer
beginner
How does
zip handle sequences of different lengths?The resulting zipped sequence stops as soon as the shortest input sequence runs out of elements.
Click to reveal answer
beginner
Show a simple example of using
zip with two arrays in Swift.Example:<br><pre>let numbers = [1, 2, 3]
let letters = ["a", "b", "c"]
for pair in zip(numbers, letters) {
print(pair)
}</pre><br>This prints:<br>(1, "a")<br>(2, "b")<br>(3, "c")Click to reveal answer
intermediate
Can you use
zip with sequences other than arrays?Yes,
zip works with any sequences, such as arrays, ranges, or strings, as long as they conform to the Sequence protocol.Click to reveal answer
intermediate
What type does
zip return in Swift?It returns a
Zip2Sequence which is a sequence of pairs (tuples) combining elements from the two input sequences.Click to reveal answer
What happens if you zip an array of 3 elements with an array of 5 elements?
✗ Incorrect
Zip stops at the shortest sequence length, so the result has 3 pairs.
Which Swift protocol must sequences conform to for
zip to work?✗ Incorrect
zip works with any type conforming to the Sequence protocol.What is the type of each element inside the zipped sequence?
✗ Incorrect
Each element is a tuple containing one element from each input sequence.
How do you access the first element of a pair from
zip?✗ Incorrect
Tuples use dot notation with index numbers, so
pair.0 accesses the first element.Which of these is a valid use of
zip in Swift?✗ Incorrect
You can zip any two sequences, such as a range and an array.
Explain how the
zip function combines two sequences in Swift and what happens if they have different lengths.Think about pairing items like matching socks from two drawers.
You got /3 concepts.
Write a short Swift code snippet using
zip to combine two arrays and print each pair.Use a for-in loop to iterate over zipped sequences.
You got /4 concepts.