ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Swift基础知识:16.Swift枚举

2026/9/20 15:39:54 拓冰建站 浏览量
Swift基础知识:16.Swift枚举

在 Swift 中,枚举(Enum)是一种用来定义一组相关值的数据类型。枚举在 Swift 中非常灵活,并且支持关联值、原始值、方法等丰富的功能。

以下是 Swift 中枚举的基本知识点和用法:

1. 定义枚举

使用 enum 关键字来定义枚举。例如,定义一个表示方向的枚举:

enum Direction {case northcase southcase eastcase west
}
2. 关联值

枚举的成员可以关联一个或多个值,这些关联值可以是不同类型的。例如,定义一个表示尺寸的枚举:

enum Size {case smallcase mediumcase largecase custom(width: Int, height: Int)
}
let mySize = Size.custom(width: 100, height: 200)
3. 原始值

枚举的成员可以有预先填充的默认值,这些默认值称为原始值。原始值可以是字符串、字符、整数或浮点数类型。例如,定义一个表示星期的枚举:

enum Weekday: Int {case sunday = 1case mondaycase tuesdaycase wednesdaycase thursdaycase fridaycase saturday
}
let today = Weekday.wednesday
print(today.rawValue)  // 输出:3
4. 递归枚举

枚举可以是递归的,即枚举成员的关联值可以是枚举类型本身。例如,定义一个表示算术表达式的枚举:

indirect enum ArithmeticExpression {case number(Int)case addition(ArithmeticExpression, ArithmeticExpression)case multiplication(ArithmeticExpression, ArithmeticExpression)
}
let expression = ArithmeticExpression.addition(.number(2), .multiplication(.number(3), .number(4)))
5. 枚举方法

枚举可以定义方法来提供与枚举关联值相关的功能。例如,定义一个枚举表示图形,然后为枚举定义一个计算周长的方法:

enum Shape {case square(side: Double)case circle(radius: Double)func perimeter() -> Double {switch self {case .square(let side):return side * 4case .circle(let radius):return 2 * Double.pi * radius}}
}
let square = Shape.square(side: 5.0)
print(square.perimeter())  // 输出:20.0

枚举在 Swift 中可以用来表示一组相关的值,例如状态、选项、错误类型等。枚举的灵活性和功能丰富性使得它成为 Swift 编程中的重要工具,用于提高代码的可读性、简化逻辑和增强类型安全性。