Did you find this helpful? Why not support me to bring you even more content.
Click here to Buy Me a Coffee and say Thanks!

DISCLAIMER: This post is older than one year and maybe out of date.

Generics – The Basics

Generics give us the type safety of Swift with strong typing but also allows us to deal with those situations where we do not always know what the type of something is going to be. Sounds a little vague right? Well let’s take a look with some code to get a better understanding of the basics.

We can also return the unknown type by returning T which will return the same type going in. In this example we are returning the last element of the array.

So if we send in an array of strings then we get a string back and if we send in an array of integers we get an integer back. So hopefully you see why Generics can be very useful, they save us from writing almost identical code over and over. In this case it saved us writing a function to handle an array of strings and another to handle an array of integers just because the types are different.