Swift Tuples
This tutorial belongs to the Swift series
Tuples are used to group multiple values into a single collection. For example we can declare a variable dog containing a String and an Int value:
let dog : (String, Int)
And we can initialize them with a name and an age
let dog : (String, Int) = ("Roger", 8)
But as with any other variable, the type can be inferred during initialization:
let dog = ("Roger", 8)
You can use named elements:
let dog = (name: "Roger", age: 8)
dog.name //"Roger"
dog.age //8
Once a tuple is defined, you can decompose it to individual variables in this way:
let dog = ("Roger", 8)
let (name, age) = dog
and if you need to just get one of the values, you can use the special underscore keyword to ignore the other ones:
let dog = ("Roger", 8)
let (name, _) = dog
Tuples are an awesome tool for various needs.
The most obvious one is a short way to group similar data.
Another one if those needs is returning multiple items from a function. A function can only return a single item, so a tuple is a convenient structure for that.
Another handy functionality allowed by tuples is swapping elements:
var a = 1
var b = 2
(a, b) = (b, a)
//a == 2
//b == 1 download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.