元组
元组
元组 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 1 节课,共 1 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 1 节课。
简介
您好,
这是一种用于以组合形式保存多个值的类型。请考虑一个函数:该函数会冻结坐标的纬度和经度信息。
与其分别返回这两个值,不如使用元组这样的高级类型,将彼此相关的两个值组合在一起,这样更符合逻辑。
警告
传递给元组的值不必属于同一种类型,例如(整数类型,字符串类型)。
示例
let http404Error = (404, "Not Found")
// http404Error is of type (Int, String),
// and equals (404, "Not Found")
let coordinates = (26, 45)
let datas = (1,2,3,4)
// The values in the tuple don't have to be just 2.
// A group can be created from more than one number of values.解构
解构元组
我们在前面的代码中定义了 http404Error。
我们可以按如下方式将这个元组解构为其中的数据。
让我们来看一下示例。
let http404Error = (404, "Not Found")
let (statusCode, statusMessage) = http404Error
// In the example below,
//String concatenation feature is seen.
print("The status code is \(statusCode)")
// Prints "The status code is 404"
print("The status message is \(statusMessage)")
// Prints "The status message is Not Found"下划线运算符
如果我们不需要元组中的某些值,可以使用下划线运算符忽略这些值。
let http404Error = (404, "Not Found")
// In the example below, since the string
//Not Found is not needed, the corresponding
//expression is passed with _ operator
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// Prints "The status code is 404"如何轻松访问元组数据
如何轻松访问元组数据
可以通过索引访问元组中的数据。
在下面的示例中,.0 表示第一个值,而 1 表示第二个值。
让我们来看一下。
let http404Error = (404, "Not Found")
print("The status code is \(http404Error.0)")
// Prints "The status code is 404"
print("The status message is \(http404Error.1)")
// Prints "The status message is Not Found"为元组值命名
可以为元组中的值指定名称。
let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http200Status.statusCode)")
// Prints "The status code is 200"
print("The status message is \(http200Status.description)")
// Prints "The status message is OK"元组尤其适合作为返回类型
元组尤其适合作为返回类型。
元组不适合用于复杂的数据结构。如果数据开始变得复杂,建议使用结构体或数据类。
恭喜您
恭喜您 🎉
本课中,我们学习了如何在 Swift 中使用元组。
下一课再见。

用 AI 导师学习 Swift — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 122
- 课程
- 409
常见问题解答
「元组」课时是免费的吗?
是的 — 「元组」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 1 节课。
「元组」这节课中我会学到什么?
元组 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Swift Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 1 节。
「元组」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Swift Academy 课中编写并运行代码吗?
能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。