Join Harrison Ferrone for an in-depth discussion in this video Tuples, part of Learning Swift 3 for Developers.
- [Instructor] For my money, Tuples are one of the most versatile variable types you'll come across in software development. They can contain different types and can be customized to take care of the most awkward of use cases with ease. Going to make some room underneath our dictionary section. And add myself a new comment, called Tuples. Let's start with a really basic tuple. var basicTuple equals. The way we do tuples in Swift is open and closed parentheses.
Now this tuple is just going to have two integers. And I'm going to say, 2 and 3, are our initial values. This is fine for a basic tuple, but what if we wanted something more complex that needed descriptions? Well, let's do that now, var descriptiveTuple equals. We're going to say our first parameter is called playerLives and our second parameter is called playerName.
Now that we've actually got some tuples, how do we go about accessing or unpacking their values? Well, let's use our descriptive tuple as an example. We'll make nother variable called firstValue. We're going to set this to descriptiveTuple.0. Perfect. If we want to unpack both values at the same time, we can do that. var and in parentheses we're going to say first and second. And those are going to be place holders for when we unpack the descriptiveTuple.
We're going to have this = descriptiveTuple. Now if we call first and second, both our values are unpacked. Using this short-hand syntax, makes unpacking complex variables really, really readable. Last, we can even declare tuples without initial values. Let's have a new variable called ourTuple and we're going to give it a type. First, it's going to be playersLives, of type Int comma playerName of type String.
This is the same as what we did with our descriptiveTuple, but in this case we're going to be able to assign the values later on. So ourTuple.playerName, we can issue to John. And ourTuple.playersLives, oh we'll give John 3. Tuples can be a really powerful tool to have. But they almost pale in comparison to the flexibility and usability of Swift enums, which we'll look at next.
- Starting a new playground
- Printing to the console
- Declaring variables
- Working with numbers
- Using strings
- Breaking down optionals
- Understanding closures
- Classes vs. structs
- Extensions and protocols