---
title: "#34: Swift Generics 🐦"
url: https://littlebitesofcocoa.com/34-swift-generics
author: Jake Marsh
date: 2015-07-09
published: 2015-07-09
topics: ["Swift"]
description: "Generics were new to many iOS developers when they debuted in Swift 1.0 last year. They are a way of specifying parts of your code can work with different..."
---

# #34: Swift Generics 🐦

By Jake Marsh, July 9, 2015. HTML: https://littlebitesofcocoa.com/34-swift-generics

**Generics** were new to many iOS developers when they debuted in Swift 1.0 last year. They are a way of specifying parts of your code can work with different kinds of objects of a given type. but you don't want to hardcode one single type. What if you wanted to say something like “this function accepts any object of some type and returns an object of that same type, but I don't care what type that is.” It ends up looking like this:

``` swift
func aGenericFunction<SomeType>(thing: SomeType) -> SomeType {
  return thing
}

aGenericFunction("Hello") // returns the String "Hello"
```

Whoa! Where did those < > brackets come from? That's how you tell the Swift compiler that you are writing a generic function. The SomeType can be any name you want, and you can use it in your code in place of a concrete type. What if you wanted your new generic function to only accept types that conformed to the a protocol? Simple: 

``` swift
func aGenericFunction<T : Requestable>(thing: T) -> T {
  return thing
}
```

Functions are great, but what about types themselves? The concepts behind **Generics** work exactly the same there. Let's look at this by making a generic DataSource struct that will power a table view controller:

``` swift
struct DataSource<ObjectType> {
  var objects = [ObjectType]()

  func objectAtIndex(index: Int) -> ObjectType {
    return objects[index]
  }
}
```

Now we can add a property to our view controllers like this:

``` swift
class SpaceshipsViewController : UITableViewController {
  var dataSource = DataSource<Spaceship>()
}
```
