📜 ⬆️ ⬇️

Swift Tuples

While searching for information about working with Tuples in Swift while working on my application, I decided that it would be better to combine all the information that I studied or found into one article so that it can be easily used.

Tuples are basically a value that can contain several other values. A composite type can also contain “named types”, which include classes, structures, and enumerations (also protocols, but since they do not store values ​​directly, I knew I should mention them separately), as well as other composite types. This means that a tuple may contain other tuples. The other composite type that a tuple can contain is a “functional type,” which is a different way to refer to a type. It describes closures in particular styles of the type “()> ()”, whose functions and methods correspond to it. Also, a functional type may contain other composite types, like a tuple, and closures, which you read about in my previous post " Closure and Definition in Swift ".


Being incompetent in technical matters, you can think of tuples as a class or structure that you can quickly write without having to define an absolute class or structure (nested or vice versa). Although according to Apple’s iBook, they should probably be used only for temporary values, as a return value from a function. Apple does not explain why, but I should have guessed that, they probably were, optimized for quick creation, due to how they are stored. However, one of the exciting new features of Swift is the return of several types, and the tuples help Swift achieve this goal, since they technically return a single value (the tuple itself).
')
Sometimes users are interested in how to pronounce the tuple in English. According to the Dictionary.com online dictionary, there are two valid pronunciations. In the phonetic transcription of the dictionary, you can see the variant / ˈtjʊpəl / and /tʌpəl/. For those who are curious, is the sound that answers the letter “oo” in the letter as in the word “took”; ə is the sound that corresponds to “a” in the letter as in the word “about”; and ʌ the sound of the letter “u” as in “gut.” This means that these sounds are pronounced (approximately) as too-puhl and tuh-puhl, respectively. I wanted to find out where their origins originate, but I only came across the fact that they are mostly part of other words like “quadruple,” “quintuple,” and “octuple” (note “tuple” ”at the end of each word). I personally prefer too-puhl.

But, I assume that the pronunciation will change, as each English-speaking country will refer to its own standard of pronunciation. Those who listen to the Accidental Tech Podcast will obviously agree with both Dictionary.com huhv-er (/ ˈhʌv ər) and hov-er (ˈhɒv- / ər) options. Those who do not listen to him, you really should do it.
Anyway, though, you didn’t come here to learn English phonetics, it’s time to learn how to use tuples in Swift!

Create a tuple

There are several ways to create tuples. Technically, I believe that one method is called the “Tuple Pattern”. It pretty much looks exactly like a literal array, except for the fact that it is in parentheses (instead of square brackets), and it can be of any type (unlike the same type in the Array):

let firstHighScore = ("Mary", 9001) 


The above method is the easiest. There is another way to create a tuple that takes advantage of Swift's named parameters. Later you will see how this method can be useful:

 let secondHighScore = (name: "James", score: 4096) 


This is really all you need to do. If it were a structure, you would have to describe the structure somewhere higher in the code, with its internal properties, etc. If it were a class, you would have to write an initializer for it yourself. All you need to do with tuples is to put the values ​​in a pair of parentheses and separate them with commas. If you really want, you can even name them for later use.

Getting data from tuples

There are several ways to read from a tuple. Which one you use will depend on where this tuple is used. You can use any of them at any time, but it is likely that in certain situations it will be easier to use one method than the other.

First, you can link the contents of a tuple using the pattern matching mechanism:

 let (firstName, firstScore) = firstHighScore 


In this case, since we use pattern matching, you can also use underscores to ignore some value if you want to use only some of them. If you wanted to get only some value from your tuple, you can do the following:

 let (_, onlyFirstScore) = firstHighScore 


They are also assigned default names, which start like indices in arrays from 0, so you can also write:

 let theName = firstHighScore.0 let theScore = firstHighScore.1 


Finally, if you have defined the name of the cortege when it was created, you can access them using a method that uses the dotted syntax:

 let secondName = secondHighScore.name let secondScore = secondHighScore.score 


Return a tuple from a function

This was discussed in my previous post “ Swift Functions: Parameters and Type of Return Value ”, but since this post contains everything you need to know about Swift tuples, I decided to combine all the information in one place.

Here is the function that returns your high score:

 func getAHighScore() -> (name: String, score: Int) { let theName = "Patricia" let theScore = 3894 return (theName, theScore) } 


Thus, we called what they would be in the meaning of the return function, and when we actually created a tuple, we should not even give it a name. Since the tuple I returned and the required tuple that was returned to the function prototype were types (String, Int), therefore the compiler did not have a problem with it. If you do not want to define them in the function prototype, this is normal, but you just have to specify the type, as well as indicating the return type, since ”(String, Int),” is also acceptable for the compiler.

If you want to additionally return a tuple, you just need to add a question mark after the type of the return value like this:

 func maybeGetHighScore() -> (String, Int)? { return nil } 


Of course, the returned tuple is optional, so you will need to expand it to use the values. You can do this through additional binding, like this:

 if let possibleScore = maybeGetHighScore() { possibleScore.0 possibleScore.1 } else { println("Nothing Here") } 


If you want to learn a little more about Optionals in Swift, read my previous post " Swift Optionals - Announcement, Unwrapping and Binding ".

There is another interesting detail to be noted about Tuples and functions, when you have a function that does not define a return value, it actually returns an empty tuple, which is simply labeled "()", just open and then the parenthesis is closed (do not use quotes , they are only needed for the layout of characters, to make them more obvious).

Access Control and Tuples

Since my posts were mainly intended to illustrate the Swift programming language, rather than full-fledged lessons (but this will change soon), we did not talk too much about access control from my first post , Swift Access Control . As soon as we immerse ourselves in the work on the lessons, they will appear much more often.

However, they do affect Swift tuples. The access level of a tuple is determined by its components and is not set directly, as you would set for a property or function. The access level of a tuple will be determined by the access level of its most limited component. Thus, if one type is private and the other is public, the access control of the tuple will be private.

Tuple - type of value

Update October 7, 2014: Thanks to the Clang developer who sent me to the post from the Apple Blog. Swift: Value type and links - Swift Blog - Apple developer , which really places the Tuple to the value type, next to structures and enumerations.

Before mentioning the above, I did a test using the playground to see if a tuple is a value type or not:

 var someScore = ("John", 55) var anotherScore = someScore anotherScore.0 = "Robert" println(anotherScore.0) //Outputs: "Robert" println(someScore.0) //Outputs: "John" 


The test really finally showed that tuples are value types. I assigned someScore to another variable called “anotherScore”. Then I changed the value for the anotherScore variable to “Robert”. When I checked what name was at anotherScore, I certainly saw “Robert”, but when I checked someScore (source variable), it still had the name “John”.

Conclusion

All code from this post was tested using the playground in xCode 6.0.1.
Now you have good information about all tuples. Initially, these parts were distributed throughout Apple's Ibook, so you will need to go to the section on tuples in the first part, on the function in the next section, and on access control in the final section. It really was appropriate that the information be in separate sections, but since we already talked about those components in this blog earlier, I only collected them all in one post.

I also wanted to thank Gavin Wiggins (@wigging on Twitter) for the updates. I clearly did not describe the tuple as an integral type, which is mentioned in the Language Reference near the end of Apple’s iBook, and he rightly stated that this should be clarified.

At first I was a little distracted by the pronunciation, but it seemed interesting to me, and I decided to share it with you. Although say it, because you like it, but do not blame someone for a different pronunciation, because both are quite acceptable. Although, for me, this post was still about too-puhls sound.

In order to continue a little more about what I mentioned in the Access Control section of this post, I plan to make even more cognitive posts in the end. I wanted to first cover more general concepts as a starting point, but then, ultimately, I would have come to the creation of lessons.

If you look at some of my posts about Objective-C, you'll see that I did mini-tutorials on how to do certain things, such as replacing the keyboard with the UIDatePicker and adding sharing to your application with the UIActivityViewController , and soon you See similar posts about the Swift language. This may be about specific classes, like UIActivityViewController, or it may be a more general post that accommodates several different parts together, like replacing the keyboard. Creating some gadgets will demonstrate other aspects of iOS programming in Swift, which will also appear soon. I will not say how soon you will begin to see such posts (or videos, maybe). They may come out next week, or in a few months, but they will.

I hope you found this article helpful. If so, please feel free to share this post on Twitter or other social networks. The blog is still pretty new, and every repost helps. Of course, if you have any questions, please contact me on Twitter @CodingExplorer, and I will see what I can do. Thank!

Source: https://habr.com/ru/post/239957/


All Articles