Show Menu

Do you have a job opening?

Submit your 30 day Job Listing for FREE

A Tuple in Swift is a neat way to store multiple values in a single value. You will probably come across tuples in a return function or class. So a tuple is basically a way to represent a collection of values that are closely linked to each other.

So here is an example of a Tuple in Swift:


var player = (“Mark”, 999, true)

The ( ) lets Swift know that you are creating a Tuple. So you would add your values into the parenthesise Tuple as above and separate them with a comma.

Like an array you can return the value using the equivalent index value like so:


Player.0  // = Mark 
Player.1 // = 999

Remember that the index value starts at 0 in arrays and Tuples

As you can see, this is not a very descriptive way to go about it. Another way to get this information and a very cool way I must say is to assign them names. This can be done like this:


var player = (name: “Mark”, score: 999, isGoldMember: true)

Now you can get them out of the Tuple like so:


Player.name // etc …

Lets say that you’re getting a Tuple back from a function or some other return and you want to decompose it by turning each of the parts into variables. You can do this easily by typing


var (name,score,isGoldMember) = player

Now you can just type put the variable name specified here, like this:


Name
Score
isGoldMember

Finally and quite possibly the coolest thing about this feature is that if you don’t want to assign a value you can just put an underscore in its place like so:


var (_, name, _)

There you have it. Go and play with Swift Tuples and see how awesome they are for yourselves.

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly


Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.


iOS-Blog Admin Team

Written by:

We're here to help.

Comments

comments