0
0
Swiftprogramming~5 mins

Zip for combining sequences in Swift

Choose your learning style9 modes available
Introduction

Zip helps you join two lists together, pairing items from each list side by side. It makes working with related data easy.

You have two lists like names and ages and want to pair each name with its age.
You want to loop over two sequences at the same time.
You need to combine two arrays into one list of pairs for easy processing.
Syntax
Swift
let zippedSequence = zip(sequence1, sequence2)

The result is a sequence of pairs (tuples).

If sequences have different lengths, zip stops at the shortest one.

Examples
This pairs numbers with letters: (1, "a"), (2, "b"), (3, "c")
Swift
let numbers = [1, 2, 3]
let letters = ["a", "b", "c"]
let zipped = zip(numbers, letters)
for pair in zipped {
    print(pair)
}
Zip stops at shortest list, so only pairs Anna and Bob with first two scores.
Swift
let names = ["Anna", "Bob"]
let scores = [95, 82, 77]
let zipped = zip(names, scores)
for (name, score) in zipped {
    print("\(name): \(score)")
}
Sample Program

This program pairs each fruit with its color and prints the pairs.

Swift
let fruits = ["Apple", "Banana", "Cherry"]
let colors = ["Red", "Yellow", "Dark Red"]

let zippedFruits = zip(fruits, colors)

for (fruit, color) in zippedFruits {
    print("\(fruit) is \(color)")
}
OutputSuccess
Important Notes

Zip creates pairs as tuples, which you can unpack in loops.

If you want to combine more than two sequences, you can zip multiple times or use other methods.

Summary

Zip combines two sequences into pairs.

It stops when the shortest sequence ends.

Use it to work with related data side by side.