Working with Tuples in Swift

Herbie Dodge
Nerd For Tech
Published in
3 min readMay 6, 2021

--

Photo by Alexandru Acea on Unsplash

When developing in Swift, every developer is familiar with named types. A named type, of course being, a type that can be named when declared. These types include Structs, Classes, Protocols, and Enumerations. Swift’s native types such as Strings, Ints, Arrays etc. are also named types and are Structs under the hood.

Along side with named types, Swift also has another type known as a compound type. Unlike its counterpart, compound types do not have names and include functions and tuples. Compound types can contain any combination of types associated with it wether it be named types, other compound types, or any other combination.The Tuple type is a set of parenthesis with commas separating its elements.

The types within the Tuple can be any type combination, making it easy to package different types of data into collection to be worked with or passed around in your code. Tuples are indexed like arrays and start at 0 as well. The elements within a Tuple can be accessed using dot notation.

It is important to note that once a Tuple’s element is declared, type safety is still enforced and it is impossible to reassign different types to its elements.

This convenient functionality makes it easier to group like data to be stored for later or passed between objects. Imagine we are working on a weather app, the URL we are using sends back a large block of JSON that provides an hourly and weekly forecast of weather data. In order to seperate the JSON into the resepective parts we need, the function we will write will return a Tuple containing two arrays of our weather data, one for hourly and weekly forecast.

Since decoding JSON can fail we flag our return type with an optional

Assuming that our decoder decodes correctly, our data will be sorted and trimmed accordingly thanks to some helper code. The function will sort the data by date then trim the first 5 items of each collection. (Our app design requires a 5 hour forecast and a 5 day forecast)

With our data sorted correctly our data is converted into our desired model object to be used, and we simply need to assign our Tuple with our new collections.

Passing our Tuple to our viewController, our data can be displayed to the user. There is a caveat to using this method: since a Tuple’s elements are not named, you must know where within the Tuple each element is. For this example it would be easier to mix up our arrays and use them in the incorrect space. Tuples make storing and passing around data a breeze especially when the data within are mixed types.

--

--

Herbie Dodge
Nerd For Tech

iOS Developer | Swift | Looking for new opportunities 🚀