Zip and Zip2Sequence in Swift

What are they, and where should they be used?

Image for post
Image for post
Photo by Jan Meeus @janmeeus

Before we start

Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 12.2, and Swift 5.3

Prerequisites

Keywords and Terminology

Tuple: A way in Swift to allow you to store multiple values in a single variable Zip: Creates a sequence of pairs created from two underlying sequences

This article

Background

You may have needed to join two different Arrays into one (same ordered) collection like in the LeetCode 211 constant.

This article explains what is going on!

The simple examples

We can zip up a couple of pairs of Integer Arrays

So the output to the console is given as the following:

This is good, because it essentially iterates over the items, and produces a resulting sequence.

Unfortunately, we are missing one important thing. Labels would be useful, and stop us having to use the Swift placeholder labels of .0 and .1.

Use a typealias to add labels

If we take each element of the Zip2Sequence to be a game, could we create a Game typealias and cast to it?

Here is the method for doing so:

which gives the output:

we can even go so far as to

So what is happening?

The zip(_:_;) method creates the same amount of pairs as the shortest sequence of the two constituent Arrays. Each element of the resulting Zip2Sequence is actually a Zip2Sequence<[Int], [Int]>.Element which doesn't have any labels.

To make these easier to work with, a tuple type is created which just those labels required, and then we can use Swift’s casting to actually use these types!

Awesome!

Conclusion

By casting Zip2Sequence there is a chance to use the rather wonderful feature of tuple types, labels. The idea is that this makes it easier for both an active programmer and a user who would need to read and understand the code as a client (that is, possibly another programmer).

I hope this helps you on your coding journey.

Thanks for reading!

If you’ve any questions, comments or suggestions please hit me up on Twitter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store