元组
元组 可以把多个值组合成一个 复合值
. 元组 中的值可以是任何类型的, 而且不必是彼茨想同的类型.
比如:
1
let http404Error = (404, "Not Found")
案例中的 元组 描述的是 HTTP 的状态码.
在 (404, "Not Found")
元组 中包含 Int
和 String
类型的变量. Int
为 HTTP 状态码, String
为 HTTP 状态的描述. 其类型为 (Int, String)
.
你可以创建 任意类型
和 不同排列
的 元组, 他可以包含任何数量不同的类型. 比如: (Int, Int, Int)
或者 (String, Bool)
.
当然, 你也可以把 元组 拆分成 变量
或者 常量
:
1
2
3
4
5
let (statusCode, statusMessage) = http404Error
print("statusCode = \(statusCode)")
// 打印结果 "statusCode = 404"
print("statusMessage = \(statusMessage)")
// 打印结果 "statusMessage = Not Found"
如果你仅需要 元组 内部分值的时候, 可以利用 _
来忽略其他的值:
1
2
3
let (justTheStatusCode, _) = http404Error
print("statusCode = \(justTheStatusCode)")
// 打印结果 "statusCode = 404"
也可以使用 索引
来访问 元组 内的值:
1
2
3
4
print("statusCode = \(http404Error.0)")
// 打印结果: "statusCode = 404"
print("statusMessage = \(http404Error.1)")
// 打印结果: "statusMessage = Not Found"
在定义元组的时候, 可以定义每个值的名称:
1
let http200Status = (statusCode: 200, description: "OK")
此时, 可以通过元组内值的 名称
来访问元素的值:
1
2
3
4
print("statusCode = \(http200Status.statusCode)")
// 打印结果: "statusCode = 200"
print("statusMessage = \(http200Status.description)")
// 打印结果: "statusMessage = OK"
元组 可以用于 方法返回多个值. 如果我们的方法需要返回多个不同的值的时候, 元组 将会变得非常有用.
注意 元组 对于简单的数据结构来说非常有用. 但是他不适合复杂的数据结构. 如果您的数据结构非常复杂, 则建议使用
结构体
或者类
, 而不是 元组.