The previous book said: the Basic Data Types of gray and often gray
Next let's look at the advanced:
Tuples
Tuples store a key value with no type restrictions
let http404Error = (404, "Not Found")// http404Error is of type (Int, String), and equals (404, "Not Found")
There is a bunch of nonsense in the book. The tuples are written in this way. The above example is a (INT, string) type, and the type in the tuples can be defined by you.
You can also separate the variable of the tuples:
let (statusCode, statusMessage) = http404Errorprintln("The status code is \(statusCode)")// prints "The status code is 404"println("The status message is \(statusMessage)")// prints "The status message is Not Found
If you only need the part value in the tuples, you can use underscores to replace unnecessary values:
let (justTheStatusCode, _) = http404Errorprintln("The status code is \(justTheStatusCode)")// prints "The status code is 404
You can also use the index to obtain the values in the tuples:
println("The status code is \(http404Error.0)")// prints "The status code is 404"println("The status message is \(http404Error.1)")// prints "The status message is Not Found
When defining a tuples, you can name the values in the tuples so that the values can be obtained using the values:
let http200Status = (statusCode: 200, description: "OK")println("The status code is \(http200Status.statusCode)")// prints "The status code is 200"println("The status message is \(http200Status.description)")// prints "The status message is OK
By the way, a very useful part of a tuples is that they can be used as the return value of a function. As mentioned in the previous article, functions in Swift can have multiple return values.
Also, tuples are not suitable for complex data combinations. If the data is too complex, use classes or struct.