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.
The Swift Programming Language (Swift 4.1): Generics
The definitive guide to Swift, Apple's programming language for building iOS, macOS, watchOS, and tvOS apps.
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.
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!
We have done two things with our new logGeneric():
- Removed the need to set an explicit array as the input type.
- We can now pass any type into the log function.
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:
- 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.
Speaking of extension we can actually extend Sequence and clean up our firstIn function. Clean code is nice code.