In the last episode we began the journey into exploring the “many faces of zip”. First we played around with the zip
that the standard library gives us a bit and saw that it was really useful for coordinating the elements of two sequences in a very safe way so that we don’t have to juggle indices.
Then we zoomed out a bit and looked at the true signature of zip
, and we saw that what it was really doing was kinda flipping containers: it transformed a tuple of arrays into an array of tuples.
After that we saw that zip
is just a generalization of map
: where map
allows us to transform a function (A) -> B
into a function ([A]) -> [B]
, zip
allowed us to transform a function (A, B) -> C
into a function ([A], [B]) -> [C]
.
This empowered us to define zip
on optionals, which is not something that people typically do. It ended up being the perfect solution to a problem that plagued Swift 1: nested if let
s! Swift 2 fixed this, but zip
still can provide a more ergonomic solution than multiple if let
s on the same line.