In Swift Language Tutorial for Beginner 3 - Control statements, we look at the control statements in Swift, and this time we’ll learn about a special data types in Swift - tuples.
In Swift Language Tutorial for Beginner 2 - Data Type, we introduce several basic types in the built-in type system in Swift, which are parts of other high-level languages, but specific keywords, with different ranges of values. But the types to be introduced today are relatively rare in other high-level languages and usually appear in dynamically interpreted languages.
Tuple
Combine multiple values into a composite value. Values within a tuple can be of any type and do not need to be of the same type. This type is much like structs in C/C++. But by definition, it’s easier to use.
Define a tuple
Here’s an example from an official document:
1 | let http404Error = (404, "Not Found") |
In this example, (404, “Not Found”) is a tuple that describes the HTTP status code. An HTTP status code is a special value returned by the web server when you request a web page. If the page you request does not exist, a 404 Not Found status code is returned.
(404, “Not Found”) Tuples combine an Int value and a String value to represent two parts of an HTTP status code: a number and a human-readable description. This tuple can be described as “a tuple of type (Int, String)”。
Of course, for the above content, we can also use different definitions, such as:
1 | let http404Error = (errCode: 200, errMessage: "Not Found") |
Of course, it can also be defined like this:
1 | let http404Error:(errCode:Int, errMessage: String) = (404, "Not Found") |
In the above definition, the type and name of each element in the ancestor are clearly indicated.
Tuple assignment
We can directly assign a value to a primitive to a variable, such as:
1 | let http404Error2 = (errCode: 200, errMessage: "Not Found") |
Of course, as long as the element’s type is the same, you can also assign an element’s unnamed tuple to an element-named tuple, such as:
1 | let http404Error = (404, "Not Found") |
Note that this is assigned to an anonymous ancestor, after which code and message can be accessed as separate variables
In the example above, if you are not interested in “code”, you can also omit code and use the placeholder: “_”. as:
1 | let http404Error = (404, "Not Found") |
Takes the value of the element
How do I take the value of an element in the Tuple? There are several ways:
- If the elements in the tuple are anonymous, you can take ordinals, such as:
1 | let http404Error = (404, "Not Found") |
- If it is a named element, you can use the first name to access it, such as:
1 | let http404Error2 = (errCode: 200, errMessage: "Not Found") |
Next
Next, we’ll briefly introduce another special types in Swift - optional - Swift Language Tutorial for Beginner 5 - Optional .