Tuples in Swift

Posted on 6/14/2014 @ 7:31 PM in #Swift by | Feedback | 1078 views

Tuples is an interesting concept. It isn’t available in ObjectiveC or C#.

It allows you tog roup multiple values into a single compound value. The values don’t even need to be of the same type. For example, this,

   1:  let vegetables = [("turnips", 5), ("carrots", 5)]

This line of code just created an array with two intances of a tuple.

I can see this being useful in many situations where for instance I am dealing with JSON data, and the overhead/botheration of creating a class is something I’d like to avoid.
C# has anonymous types which get around that issue, but they are nearly not as flexible – for instance, I cannot return anonymous types from a method, tuples I can.

You can also decompose a tuple quite easily into normal variables as below,

   1:  var (myvegetablename, myvegatablecount) = vegetables[0]

If you want only certain variables, you can do the following,

var (myvegetablename, _) = vegetables[0]

Functions can also return (or accept) tuples, as below,

   1:  func getWeatherForecast() -> (max:Int, min:Int, humidty:Float) {
   2:      return (55,20,88.8)
   3:  }
   4:   
   5:  getWeatherForecast()

Sound off but keep it civil:

Older comments..