Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Understanding tuples

Writing if statements Написание если заявления | Using the switch statement | Using the switch statement Использование Переключатель | Creating loops in Swift | Creating loops in Swift Создание петель в Swift | Defining functions | Defining functions Определение функции | Creating and using arrays | Creating and using arrays Создание и использование массивов | Using dictionaries |


Читайте также:
  1. Understanding access modifiers in Swift
  2. Understanding access modifiers in Swift
  3. Understanding the reading
  4. Understanding tuples Понимание кортежи

 

- This term, like a lot in computing, originally comes from mathematics. Even the most math-phobic individuals should not be worried, it's an easy concept. A tuple or tuple is a group of elements a few values collected together, and that's all it means. Think of the terms double for two of something, triple for three, quadruple for four, quintuple for five, sextuple for six, septuple, octuple, et cetra. That's where this word tuple or tuple comes from. Sidebar, okay, I have to take a moment on pronunciation. You will hear this word pronounced as tuple, or as tuple, or indeed sometimes as tuple.

It seems to depend on when and where, including which side of the Atlantic you learned it in. Whether you first heard it in a programming situation or in a pure mathematics one. I first learned this word as tuple many years ago. If you prefer tuple or tuple, be my guest. I have no dog in this fight. Figure out how you would naturally say words like this, and pick your pronunciation accordingly. Tomato, tomato et cetra. End of sidebar, let's get back to Swift. A tuple is a quick and easy way to group values together.

Maybe two, maybe three, maybe four, maybe more them, and just pass them all around as a single item, without having to go to the formality of creating a struct, or a class, or loading these values into an array, or any other kind of formalized data structure. It is intentionally simple. All we do is gather the values we want, whether they are variables, or constants, or even just literal values, and put them in parenthesis separated by commas. So, over to X-code the new playground, if I had a couple of standard variables or constants, I could combine them into a tuple like this.

Just create a new variable, and put them inside parenthesis separated by commas. That's it. I've just made made a tuple. This variable named my tuple represents this single compound value, that itself contains two elements gathered together. I could do it with even more values. We can gather variables, constants, and literal values like this. So, a tuple can be multiple integer values, multiple Strings, or a miss-mash of different types, whatever you need at the time. Here's the thing, most of the time you won't actually need to make a tuple variable like I've done here.

You'll just use the parenthesis to gather some values together when it's useful to do so. In fact, our first tuple was when we were iterating through a (dictionary) just creating a simple dictionary here. We saw that when we were doing a for-in loop, when we do this, what we got each time around the loop is a tuple. It's a compound value that itself contains two pieces of information. So, here the abbreviation comma full name. This is a tuple. In this code I'm providing my own temporary name for each part of this, which I can then use inside the body of the (for it).

Doing this is called decomposing the tuple. We are accessing each inner element of that. Here's another example I'm going to us. When defining a function, we've all ready seen how to return a single value from a function, whether that's a String or an integer, whatever you need to do. You're just using the return arrow, and then naming the type. The information that you're returning. If I wanted to define a function that instead returns a tuple, returns multiple pieces of information combined into one, that's pretty simple to do as well.

We use the return arrow, and then we just put the types of the data that we want to return inside parenthesis separated by commas. So, instead of just returning a String, we now return a tuple that contains a String and an integer. We can return any kinds of data type in a tuple. We need to define those types in the order their in, so anyone calling this function will know what to expect. In my example here, I've just directly made a tuple in the return statement returning a String comma integer. Now, the question is, how do we call this? When we're calling this function, what do we do, what do we get, and how do we deal with it? Well, there's a couple of different options here.

I could do something like this. Calling the function and retrieving it into a new constant in this case. Let result equal whatever comes from get current song and duration. So, result will be the return tuple as a single compound value. I want to be able to get into that tuple to decompose it to get to the values that I know are inside it, the String and the integer. Say, if I wanted to just use it to write out a message, I have a couple of choices. So, I'm wanting to write out a message here, with the name of a song and its length.

Well, I know the tuple itself is called result. One of the options that I have is using an index number. You can think of the tuple as being a really simplistic array. I can use result.0 for the first part, and result.1 for the second. We pull those two pieces of information out of the tuple and show them in our print message. Well that works, but there's another more friendly option, is that up here where I'm finding the function that returns this tuple, I could actually provide a friendly name for each element in that.

So, before the String type, I'm going to say name:String and length:int. Now down here in the message, I'm retrieving result. That'll be the tuple, but it will have a name and a length property. So, I can say result.name, and that is result.length seconds long. Same information but a bit friendlier way to write it. As straight-forward as this is, there's even a simpler way to deal with the tuples that you get when you're calling a function.

So, let me comment out this code. What I'm going to show is, I'm going to call this function and decompose the tuple immediately, breaking it apart as I'm calling the function. Here's what I mean by that. Instead of the two steps of first retrieve the tuple with a specific name, and then use that name to break it apart, I simply do this. Create a new decompose tuple variable by calling this. I'm using the parenthesis to tell Swift that I fully expect a tuple return from this function call.

I don't care about naming the tuple itself, but these are the two names that I want to use for each inter element of that tuple. These names are whatever I want. They don't have to match anything written in the function definition. They do right now, but even if I hadn't had those defined in the function definition, this would work just fine. It's returns a String and an integer, I will call them name and length. I can use that information just to get directly to those parts of the tuple. The song is name, and its length seconds long.

Just double checking with the quick look, and we see the full message. Looks fine. That is the best intro to tuples that I can think of. They are very common in Swift. They're quick to create. They're quick and easy to use. It's important to understand tuples aren't intended to replace more formal data structures, they are simply a conveniently way to temporarily group a few values together. If the data you're grouping together actually belongs together, and you find yourself grouping the same data the same way in multiple places in your application, then you should probably be looking at a class or a structure, but we'll get to those a little later.

 

 


Дата добавления: 2015-08-20; просмотров: 82 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Using dictionaries Использование словарей| Understanding tuples Понимание кортежи

mybiblioteka.su - 2015-2024 год. (0.007 сек.)