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.

Share Button
  • The problem with using theArray[theArray.count-1] is that if the function is passed an empty array you’ll have a crash.

    My solution would be to return an optional T? and then change this code:

    let lastItem: T = theArray[theArray.count-1]
    return lastItem

    to simply return theArray.last

    • Thanks Anthony,

      That is indeed a great idea and well spotted, I did not notice the loophole.

      Don’t you just love using those optionals!

Signup for my Free Swift Newsletter