Topics

#34: Swift Generics 🐦

Topics

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:

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:

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:

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:

class SpaceshipsViewController : UITableViewController {
  var dataSource = DataSource<Spaceship>()
}