Fun With Maps

Fun With Maps

by Daniel Pratt

A really cool feature in Swift are enclosures, basically a function within a function.  These are used in many built in functions, like map, reduce, filter, and sorted to name a few.  I had come across these functions before, but never really knew how to use them.

I had run across the map function before, but had never played around with it to the point of understanding.  Essentially, a map allows you to manipulate, or pull data out of a collection, such as an array.

For example:

This takes an array of Ints and creates a new array of Strings called "numbersAsStrings" and maps the bids array into String values.  The new array now holds an array of strings that looks like: ["48", "75", "63", "52", "6"].

My favorite feature of map (same is true for the other functions mentioned above) is that you can allow Swift to infer a lot of things.  This means that I can do the exact same thing by declaring my array of String versions of numbers this way:

The main thing I wanted to talk about in this blog post is how to use map to update values inside of an instance.

Let's say I have the following struct:

And now I can instantiate an array of this with

If I wanted to create a new StuffWithNumbersAndStrings object where each value was increased by a certain number, let's say 10, then I should be able to use map like this:

This actually produces an error.  The way that swift handles the inference that lets you use $0,  $1, etc makes these values immutable and saying:

This just creates an array of Ints.  They have the right values, but we wanted a new instance of StuffWithNumbersAndStrings.  I don't know why it took me so long to figure out, but I finally came up with what I think is the cleanest solution:

This gives us what we want.  An array that is the same as the original array, we've just updated the numbers values in the instances contained within the array.

They say that the best way to retain what you have learned is by sharing it with others.  I hope this post helps you out to read as much as it helped me to write!


Popular posts from this blog

Passing Information Between View Controllers

Landing Your First iOS Developer Job: My Journey Changing Careers

Stars... They're What Growing Developers Eat for Breakfast