UX Development & Design

Taylor’s Swift: Favorite Things – Generics

Raindrops on roses and whiskers on – Wait, that’s not it. I’m back with more thoughts on Swift. In the next few posts, I’ll talk about some of the pleasures of working in Swift (hence, a few of my favorite things). I’ll be using Objective-C as my baseline for comparison. Many of the things I’ll mention exist elsewhere and inspired Swift to be as awesome as it is. Topic for today: generics.

One of the coolest things that Swift brings with it is the concept of generics. These are found in other languages, but it’s not something we’ve had in Objective-C until very recently, so it’s a new idea for the Apple development world. This is a more advanced topic, and one I intend to write more about later, but I’ll try to cover the basics now.

Typically, if we’re passing a value to a function, the function has an explicit expected type for each value that we’re sending it. Imagine if you had to build a function to add two numbers together. This seems simple enough, but if you consider that integers (1, 2, 42) are a different type from floating point numbers (1.2, 2.3, 42.0), it quickly becomes apparent that you would have to write two functions to handle those two types. Another type would require another function, and so on. That quickly becomes cumbersome to deal with as changes are needed. Generics allow us to write one function to support multiple types. Generics to the rescue!

 

func add <GenericType> (item1: GenericType, item2: GenericType) 
    -> GenericType {
        return item1 + item2
}

 

We just feed this function two items of the same type (likely numbers, but maybe other types as well) and we’ll get the result of using the + operator on them. If we find a bug to fix or improvement to make in our code, we only have one place where we have to do our work. Generics give us an obvious way to write more flexible code; we just have to know when and how to use them. Tools that make my life easier and also make my code structure better? That makes me happy. I hope it makes you happy too.

Keep an eye out for more of my favorite things about Swift, and more detailed posts on our Swift blog. I hope you’re enjoying them, and have fun on your adventures in Swift!

By Taylor Smith