More On Swift Generics

Martin
Martin
Mar 5, 2018 · 3 min read

What is this? Another post on generics? Naturally, yes.

At a base level generics are exactly what the word implies, generic. It can be anything and everything. Functions that use generics compile down to the type that is given which allows you to act upon an explicit type, e.g, String or Int. Here is the first paragraph from the Apple Swift Language Guide:

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.

If you are keen on reading the documentation, which I will always recommend you do, and coming back perfect, otherwise if you want to jump right into it lets get started with this example just to get your feet wet.

old and busted.

A simple function that prints the values in a given array. However given anything other than Int the compiler will error out by being given an unexpected type.

Generics to the rescue!

the new hotness.

We have done two things with our new logGeneric():

  1. Removed the need to set an explicit array as the input type.
  2. We can now pass any type into the log function.

More Please

Ok, so now that we have a base understanding of what Generics are lets look at a more in depth example. Say we want to bring back constraints and are looking for the first item in an array. Here is a base function that we can expand on:

This functions does a few things, so lets break it down:

  1. It takes an array of Any with a Generic Type:

2. Flattens the array:

3. And returns the first element:

So with this new function you can do something like this:


So this is good but we still want more…

What if we want to make sure this function can only be called for certain types? For instance, what if we only want Int as we will be doing some math later in the code?

In that case Protocol is coming to the rescue.

Now we are back in business! We now have the confidence that your future self won’t change anything and keep you safe and sound. Thanks past self for looking out. So with that I hope you have a better understanding of how Generics work in Swift.


Bonus 🎉

Speaking of extension we can actually extend Sequence and clean up our firstIn function. Clean code is nice code.

mrtnrst

Life as a developer all told by quips, longform, and gifs

Martin

Written by

Martin

Programmer. Designer. And pretty much anything else that floats my boat. -arista™

mrtnrst

mrtnrst

Life as a developer all told by quips, longform, and gifs