枚举
枚举
枚举 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 1 节课,共 1 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 1 节课。
简介
您好,
本课中,我们将学习枚举这一主题。
枚举用于创建用户定义的类型。在下一步中,通过使用这些用户定义的关联数据,我们可以编写类型安全性更高的代码。
枚举是用于将同一相关组中的数据集中保存的值类型。它使我们能够在代码中实现类型安全。
续
关于枚举,有一些信息是我们需要了解的。让我们一一列出。
- 在 Swift 中,枚举中的每个分支都不必具有值。
- 分配给枚举分支的原始值可以是字符串、字符、整数或浮点类型。
- 我们可以在枚举中定义 AssociatedValue。这些定义的值可以是任意类型。
- 枚举在 Swift 中是一等类型。
续
- 我们不必为枚举中的每个分支定义值,也就是原始值。枚举是一等类型。我们可以为其添加属性、方法或初始化器。
- 可以通过实现协议和编写扩展来实现枚举。
- 枚举名称必须以大写字母开头。
- 枚举是值类型,而不是引用类型。
enum SiliconValley {
case Google
case Apple
case Microsoft
}
enum SiliconValley1 { case Apple, Google, Amazon, Microsoft}
var companyName = SiliconValley1.Apple
companyName = SiliconValley1 . Google
companyName = .Amazon
/*
After the first definition, he realized that the
variable companyName type is the SiliconValley1 enum.
As in the .Amazon definition in the last line,
there is no need to pass the name of the enum as an extra.
companyName is automatically inferred.
*/rawValue
我们也可以在枚举中定义原始值。
让我们通过示例来学习。
enum Direction1: String {
case North, South, East, West
}
//Default value of North = “North”
//Default value of South = “South”
//Default value of East = “East”
//Default value of West = “West”
enum SiliconValley2: Int {
case Apple, Google, Amazon, Microsoft
}
//Default value of Apple = 0, Google =1, Amazon =2 , Microsoft =3
示例
现在,让我们明确演示原始值的用法。
enum Direction2: Character
{
case North = "n"
case South = "s"
case East = "e"
case West = "w"
}
enum SiliconValley3: Int {
case Apple = 1 , Google, Amazon, Microsoft
}
// value of Google = 2, Amazon = 3, Microsoft = 4
// Defined Enum Raw Value can be accessed as follows.
enum SiliconValley4: Int { case Apple = 1 , Google, Microsoft, Amazon }
let companyRank = SiliconValley4.Amazon.rawValue
print ( "Raw value of Amazon is \(companyRank)" )
//Prints Raw value of Amazon is 4”恭喜您
恭喜您 🎉
本课中,我们学习了Swift 中的枚举。
下一课再见。

常见问题解答
「枚举」课时是免费的吗?
是的 — 「枚举」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 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 反馈 — 无需本地设置。