iOS Development Swift Chapter-(v) Tuple types
I. Introduction to the type of meta-group
1. What is a tuple type
A tuple type consists of n arbitrary types of data (n >= 0), and the data that makes up the tuple type can be called an "element"
Example:
Let position = (x:10.5, y:20)//position has 2 elements, X, Y is the name of the element
Let person = (name: ' Jack ')//person only name one element
Let data = ()//Empty tuple
2. Access to elements
var position = (x:10.5, y:20)
(1) with element name
Let value = position.x//value
POSITION.Y = 50//Set Value
(2) position with element
var value = position.0//equivalent to var value = postion.x
POSITION.1 = 50//equivalent to POSTION.Y = 50
code example:
Note: If you use let to define a tuple, then it is a constant and you cannot modify its elements
Let point = (X:10, y:20)
Point.x = 30
The 2nd line of code will error
code example:
3. Meta-Set output
You can output an entire tuple to see the values of all the elements
var point = (x:10.5, y:20)
Point.x = 30
Point.1 = 50
println (Point)
The output is:(30.0, +)
Second, the use of details
(1) Element name can be omitted
Let position = (10, 20)
Let person = ("Jack")
(2) The type of the element can be specified explicitly
var person: (Int, String) = (all, "Rose")
The No. 0 element of person can only be of type int, 1th element can only be string type
Note: You cannot add an element name when you explicitly specify an element type
Therefore, the following statement is incorrect
var person: (Int, String) = (age:23, name: "Rose")
(3) can receive tuple data with multiple variables
var (x, y) = (ten, +)//X is 10,y is 20
var point = (x, y)/A point consists of 2 elements, 10 and 20, respectively
(4) You can assign elements to multiple variables individually
var point = (10, 20)
var (x, y) = point
X is 10,y is 20
(5) You can use the underscore _ to ignore the value of an element and to remove the value of another element
var person = ("Jack")
var (_, name) = person
The content of name is "Jack", and element 20 in person is ignored
iOS Development Swift Chapter-(v) Tuple types