0
0
Swiftprogramming~20 mins

Zip for combining sequences in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Zip Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Swift code using zip?

Consider the following Swift code that uses zip to combine two arrays. What will be printed?

Swift
let numbers = [1, 2, 3]
let words = ["one", "two", "three"]
for (number, word) in zip(numbers, words) {
    print("\(number): \(word)")
}
Aone: 1\ntwo: 2\nthree: 3
B1: one\n2: two
C3: three\n2: two\n1: one
D1: one\n2: two\n3: three
Attempts:
2 left
💡 Hint

Remember that zip pairs elements from both sequences in order.

Predict Output
intermediate
2:00remaining
What happens when zipping sequences of different lengths?

What will be the output of this Swift code?

Swift
let a = [10, 20, 30, 40]
let b = ["a", "b"]
for (num, letter) in zip(a, b) {
    print("\(num)\(letter)")
}
A10a\n20b
B10a\n20b\n30c\n40d
C30c\n40d
D10a\n20b\n30\n40
Attempts:
2 left
💡 Hint

Think about how zip handles sequences of different lengths.

🔧 Debug
advanced
2:00remaining
Why does this Swift code using zip cause a runtime error?

Examine the code below. Why does it cause a runtime error?

Swift
let nums = [1, 2, 3]
let words = ["one", "two"]
let zipped = zip(nums, words)
let array = Array(zipped)
print(array[2])
AType error because zipped is not convertible to Array
BSyntax error because zip requires sequences of equal length
CIndex out of range error at runtime because zipped has only 2 elements
DNo error, prints (3, "three")
Attempts:
2 left
💡 Hint

Check how many elements zipped contains and what index is accessed.

🧠 Conceptual
advanced
2:00remaining
What is the type of the result of zip in Swift?

Given two arrays a and b, what is the type of zip(a, b) in Swift?

ASequence<(Int, String)>
BZip2Sequence<Array<Int>, Array<String>>
C[(Int, String)]
DArray<(Int, String)>
Attempts:
2 left
💡 Hint

Think about what zip returns before converting to an array.

🚀 Application
expert
3:00remaining
How to sum pairs of numbers using zip in Swift?

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?

Alet sums = zip(arr1, arr2).map { (a, b) in a + b }
Blet sums = zip(arr1, arr2).map { $0 + $1 }
Clet sums = zip(arr1, arr2).map { $0 * $1 }
Dlet sums = arr1.enumerated().map { $0.element + arr2[$0.offset] }
Attempts:
2 left
💡 Hint

Remember the closure syntax for map when using zip.