On Typed Tuples in Swift

Tuples are a wonderfully powerful thing... from iterating a dictionary getting both key and value

for (key,value) in myDictionary{
  println("My key is \(key) and it has a value of \(value)")

To returning richer data from functions

func getResponse()->(responseCode:Int,payload:String?){
  // Do stuff
  return (404,nil)

All the way to augmenting enums

enum ServerResposne{
  case Error(Int)
  case Success(String)
let response = ServerResponse.Error(404)

I have found them particularly useful when you don't want to define an entire new type (be it struct, enum or class), but do need to compose a couple of things together into a package (our second case, richer data from functions). However, like so many convinces they come at a cost when you think about future you. You are both dependant on nice meaningful variable names, and even though you can name the fields of the tuple, you can't provide a hint as to exactly what the tuple is intended to encapsulate. You don't get compiler type checking, and if you decide to replace them there is no way to easily identify everywhere that particular structure is used. 

Except of course there is a one line way to protect against all of these issues, just define the tuple as a type alias

typealias ServerResponse = (responseCode:Int,payload:String?)

That's it. Now if you decide you want to capture this in a stronger type you can just replace that alias with the desired type, and the compiler will pick out everything that needs updating as a result. If you are lucky, that may even just be fixing the places where the tuples were created and the rest will just fall out. 

So we have a rule, if a tuple leaves a function scope (or greater), it gets a typealias. It's been a wonderful way of avoiding unnecessary additional types, but allowing your code to grow into them if needed.