Swift – 元组
元组是一个常量或变量,可以容纳一组值,这些值可以是不同的数据类型并复合为单个值。简单来说,元组是一种可以保存不同数据类型的多个值的结构。元组通常用作返回值,以从任何进程的输出中检索各种数据。
为了创建元组,首先在 Swift 中声明一个元组,我们在代码中声明一个常量或一个变量,然后将数据直接输入到用逗号分隔的圆括号中。下面是元组的基本结构,其中 data1、data2、data3、……、dataN 都可以是相同或不同的数据类型。
执行:
示例 1:声明一个包含字符串和整数的元组
// statusLoad is of type (String, Int), and equals to (“Forbidden”, 403)
let statusLoad = (“Forbidden”, 403)
因此,这些数据有两种形式:String(人类可读的描述)和 Int(数字)。
我们可以从任何数据类型的排列中创建一个元组,并且它们可以包含任意数量的各种类型。意思是,一个元组可以保存任意数量的相似或不同数据类型的数据。
示例 2:声明一个包含字符串的元组
let a = (Int, Int, Int, Int)
var b = (String, Int, String, Int, Int)
此外,我们可以命名元组中的单个元素,如下例所示
示例 3:
let statusLoad = (tupleMessage: “Forbidden”, tupleCode = 403)
Now in order to decompose a tuple in swift, it is done and split into variables or constants . We can access the data in a tuple by decomposing it into constants and variables
如下图所示:
示例 4:
// refer statusLoad from above
let (sMessage, sCode) = statusLoad
// prints the message “Forbidden”
print(“The status message is \(sMessage).”)
// prints the code “403”
print(“The status code is \(sCode).”)
输出:
The status message is Forbidden.
The status code is 403.
Note: Additionally, we can access a specific element inside a tuple by replacing the unwanted data positions with an underscore (_).
示例 5:
let (sMessage,_) = statusLoad
print(“The status message is \(sMessage).”)
// prints the message “Forbidden”
let (_, sCode) = statusLoad
print(“The status code is \(sCode).”)
// prints the code “403”
输出:
The status message is Forbidden.
The status code is 403.
Note: Alternatively, we can access the data using indexed numbers. These numbers start from 0, meaning that we need to pass n-1 indexed term to access the nth element.
示例 6:
let sMessage = statusLoad.0
// prints the message “Forbidden”
print(“The status message is \(sMessage).”)
let sCode = statusLoad.1
// prints the code “403”
print(“The status code is \(sCode).”)
输出:
The status message is Forbidden.
The status code is 403.
请参考上面的示例 3:
Note: We can also access every individual element by their names as shown:
示例 7:
let statusLoad = (tupleMessage: “Forbidden”, tupleCode = 403)
// prints the message “Forbidden”
print(“The status message is \(statusLoad.tupleMessage).”)
// prints the code “403”
print(“The status code is \( statusLoad.tupleCode).”)
输出:
The status message is Forbidden.
The status code is 403.