Sling Academy
Home/Swift/Using the zip() function in Swift

Using the zip() function in Swift

Last updated: May 08, 2023

Overview

In Swift, the zip() function is used to create a sequence of pairs built out of two underlying sequences, where the elements of each pair are the corresponding elements of each sequence. If the two input sequences have different lengths, it will use the shorter one as the limit.

Syntax:

func zip<Sequence1, Sequence2>(
  _ sequence1: Sequence1,
  _ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2>
where Sequence1 : Sequence, Sequence2 : Sequence

Where:

  • sequence1: The first sequence or collection to zip. This can be any type that conforms to the Sequence protocol, such as an array, a range, a string, etc.
  • sequence2: The second sequence or collection to zip. This can be any type that conforms to the Sequence protocol, such as an array, a range, a string, etc.

The zip() function returns a value of type Zip2Sequence, which is a special type that conforms to the Sequence protocol and stores both sequences internally. This type can be used in a for-in loop or with other methods that work with sequences.

Examples

Learning by example is one of the best ways to get a deep understanding of the zip() function.

Comparing two arrays of scores

A common use case of the zip() function is to iterate over two sequences at the same time and perform some operation on their corresponding elements. For example, you are a teacher, and you have two arrays containing the scores of students on two recent tests. What you want is the average score of each student.

let scores1 = [80, 90, 75, 85]
let scores2 = [85, 95, 70, 80]


for (score1, score2) in zip(scores1, scores2) {
    let averageScore = (score1 + score2) / 2
    print("Average: \(averageScore)")
}

Output:

Average: 82
Average: 92
Average: 72
Average: 82

Creating a new sequence by combining two sequences

In this example, we have two arrays. The first array contains the names of some boys. The second array contains the names of some girls. What we will do is use the zip() function to create an array of tuples where each tuple contains a couple of a boy and a girl.

let boys = ["Boy 1", "Boy 2", "Boy 3"]
let girls = ["Girl 1", "Girl 2", "Girl 3"]

let couples = Array(zip(boys, girls))
print(couples)

Output:

[("Boy 1", "Girl 1"), ("Boy 2", "Girl 2"), ("Boy 3", "Girl 3")]

Next Article: Creating Dictionaries in Swift (with Examples)

Previous Article: Swift: How to Convert an Array to JSON

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)