Consider the following Swift code that uses zip to combine two arrays. What will be printed?
let numbers = [1, 2, 3] let words = ["one", "two", "three"] for (number, word) in zip(numbers, words) { print("\(number): \(word)") }
Remember that zip pairs elements from both sequences in order.
The zip function pairs elements from numbers and words by their positions. So the first pair is (1, "one"), second is (2, "two"), and third is (3, "three"). The loop prints each pair in order.
What will be the output of this Swift code?
let a = [10, 20, 30, 40] let b = ["a", "b"] for (num, letter) in zip(a, b) { print("\(num)\(letter)") }
Think about how zip handles sequences of different lengths.
The zip function stops when the shortest sequence ends. Here, b has only 2 elements, so only two pairs are formed.
Examine the code below. Why does it cause a runtime error?
let nums = [1, 2, 3] let words = ["one", "two"] let zipped = zip(nums, words) let array = Array(zipped) print(array[2])
Check how many elements zipped contains and what index is accessed.
The zip pairs only up to the shortest sequence length, so zipped has 2 elements. Accessing array[2] causes an index out of range runtime error.
Given two arrays a and b, what is the type of zip(a, b) in Swift?
Think about what zip returns before converting to an array.
The zip function returns a Zip2Sequence type that lazily pairs elements from the two sequences. It is not an array until converted.
You have two arrays of integers: arr1 and arr2. You want to create a new array where each element is the sum of the corresponding elements from arr1 and arr2. Which code snippet correctly does this using zip?
Remember the closure syntax for map when using zip.
Option A correctly uses zip to pair elements and a closure with two parameters to sum them. Option A is incorrect because $0 is a tuple, so $0 + $1 is invalid. Option A works but does not use zip. Option A multiplies instead of sums.