Zip and Zip2Sequence in Swift
Before we start
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 12.2, and Swift 5.3
- You’ll need to either be able to write an iOS application or write some Swift code in Playgrounds
- Some knowledge of Tuple types would be useful for this article
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
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
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?
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!
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