Swift 枚举类型,你知道几个?

开发 前端
本文我们介绍了在 Swift 中如何定义枚举、遍历枚举、枚举原始值、枚举关联值等相关的内容。通过与 TypeScript 语法的对比,希望能帮助您更好地理解 Swift 的相关特性。

本文我们将介绍在 Swift 中如何定义枚举、遍历枚举、枚举原始值、枚举关联值等相关的内容。如果你尚未安装 Xcode 和配置 Swift 开发环境,请您先阅读这篇文章。

接下来,我们启动 Xcode,然后选择 "File" > "New" > "Playground"。创建一个新的 Playground 并命名为 "Enumerations"。

在 Swift 中,枚举(Enum)是一种特殊的数据类型,它允许你定义一组相关的值。这些值是你在程序中会用到的一些具体选项。

定义一个枚举

在 Swift 中,我们使用 enum 关键字定义一个枚举,在枚举体内使用 case 关键字定义不同的情况,每个情况表示枚举的一个成员。

Swift Code

enum Color {
    case red
    case green
    case blue
}

let greenColor = Color.green

print(greenColor)
// Output: green

在以上代码中,我们定义了一个名为 Color 的枚举,包含了三种颜色。

TypeScript Code

enum Color {
    Red,
    Green,
    Blue
}

let color: Color = Color.Green;

console.log(color);
// Output: 1

使用 switch 处理枚举

有了 Color 枚举后,我们可以使用 switch 语句来处理枚举。

Swift Code

enum Color {
    case red
    case green
    case blue
}

func describeColor(color: Color) {
    switch color {
    case .red:
        print("Color is red.")
    case .green:
        print("Color is green.")
    case .blue:
        print("Color is blue.")
    }
}

describeColor(color: .blue)

// Output: Color is blue.

TypeScript Code

enum Color {
    Red,
    Green,
    Blue
}

function describeColor(color: Color): void {
    switch (color) {
        case Color.Red:
            console.log("Color is red.");
            break;
        case Color.Green:
            console.log("Color is green.");
            break;
        case Color.Blue:
            console.log("Color is blue.");
            break;
    }
}

describeColor(Color.Blue);

// Output: "Color is blue."

遍历枚举的成员

在 Swift 中,我们可以使用 CaseIterable 协议来使枚举遵循可迭代的协议,从而实现对枚举成员的遍历。

Swift Code

enum Color: CaseIterable {
    case red, green, blue
}

for color in Color.allCases {
    print(color)
}

/**
Output: 
red
green
blue
*/

在上面的代码中,我们让 Color 枚举遵循 CaseIterable 协议,以便枚举该枚举的所有成员。

TypeScript Code

enum Color {
    Red,
    Green,
    Blue
}

for(let colorKey in Color) {
    console.log(colorKey)
}

/**
Output: 
"0" 
"1" 
"2" 
"Red" 
"Green" 
"Blue" 
*/

枚举原始值

Swift 中的枚举可以关联原始值,这些原始值可以是整数、浮点数、字符串等类型。枚举的原始值为每个成员提供了一个默认值,方便我们在不同的上下文中使用。

数值原始值

Swift Code

enum Weekday: Int {
    case sunday = 1
    case monday
    case tuesday
    case wednesday
    case thursday
    case friday
    case saturday
}

let today: Weekday = .tuesday
let rawValue: Int = today.rawValue

print(rawValue)
// Output: 3

在以上代码中,我们定义了一个表示星期的枚举 Weekday,并为每个成员显式赋予了一个原始值。默认情况下,第一个成员的原始值为 1,后续成员的原始值递增。

TypeScript Code

enum Weekday {
    Sunday = 1,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

let today: Weekday = Weekday.Tuesday;
let rawValue: number = today;

console.log(rawValue);
// Output: 3

在 TypeScript 中,数值枚举的原始值也是递增的,与 Swift 中的数值枚举相似。

字符串原始值

Swift Code

enum Direction: String {
    case up = "UP"
    case down = "DOWN"
    case left = "LEFT"
    case right = "RIGHT"
}

let move: Direction = .up
let directionString: String = move.rawValue

print(directionString)
// Output: UP

在以上代码中,我们定义了一个字符串枚举 Direction,为每个成员显式赋予了一个字符串原始值。

TypeScript Code

enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT"
}

let move: Direction = Direction.Up;
let directionString: string = move;

console.log(directionString);
// Output: "UP"

字符串枚举的原始值在 TypeScript 中也是类似的,允许为每个成员指定字符串类型的原始值。

枚举关联值

Swift 中的枚举不仅可以有原始值,还可以携带关联值。关联值允许在定义枚举的时候指定每个成员携带的数据类型。这样,每个枚举成员都可以携带不同类型的数据。

Swift Code

import Foundation

// 定义 Shape 枚举描述不同的图形
enum Shape {
    case circle(radius: Double)
    case square(side: Double)
    case rectangle(width: Double, height: Double)
}

// 使用关联值创建不同的图形
let circle: Shape = .circle(radius: 3.0)
let square: Shape = .square(side: 4.0)
let rectangle: Shape = .rectangle(width: 3.0, height: 4.0)

在以上代码中,我们定义了一个 Shape 枚举,其中的每个成员都可以携带不同类型的关联值,表示不同的图形。有了 Shape 枚举之后,我们可以创建一个 calculateArea 函数,来计算不同图形的面积。

Swift Code

func calculateArea(shape: Shape) -> Double {
    switch shape {
    case .circle(let radius):
        return Double.pi * pow(radius, 2)
    case .square(let side):
        return pow(side, 2)
    case .rectangle(let width, let height):
        return width * height
    }
}

// 计算不同图形的面积
let areaOfCircle = calculateArea(shape: circle) // 28.27433388230814
let areaOfSquare = calculateArea(shape: square) // 16
let areaOfRectangle = calculateArea(shape: rectangle) // 12

在以上代码中,我们定义了一个函数 calculateArea,根据图形的类型计算图形的面积。通过关联值,我们可以轻松地提取不同图形的属性进行计算。在 TypeScript 中,由于并没有直接对应 Swift 枚举关联值的语法,我们可以使用 TypeScript 的联合类型来模拟这种行为。

TypeScript Code

interface Circle {
    kind: 'circle';
    radius: number;
}

interface Square {
    kind: 'square';
    side: number;
}

interface Rectangle {
    kind: 'rectangle';
    width: number;
    height: number;
}

// 使用联合类型表示不同的图形
type Shape = Circle | Square | Rectangle;

在以上代码中,我们使用接口和联合类型来定义不同图形的数据结构。之后,我们也可以定义一个 calculateArea 函数来计算不同图形的面积。

TypeScript Code

function calculateArea(shape: Shape): number {
    switch (shape.kind) {
        case 'circle':
            return Math.PI * Math.pow(shape.radius, 2);
        case 'square':
            return Math.pow(shape.side, 2);
        case 'rectangle':
            return shape.width * shape.height;
        default:
            throw new Error('Invalid shape');
    }
}

const circle: Circle = { kind: "circle", radius: 3.0 }
const square: Square = { kind: "square", side: 4.0 }
const rectangle: Rectangle = { kind: "rectangle", width: 3.0, height: 4.0 }

// 计算不同图形的面积
const areaOfCircle = calculateArea(circle); // 28.274333882308138
const areaOfSquare = calculateArea(square); // 16
const areaOfRectangle = calculateArea(rectangle); // 12

枚举中定义计算属性

Swift Code

enum Color {
    case red, green, blue

    var hexValue: String {
        switch self {
        case .red:
            return "#FF0000"
        case .green:
            return "#00FF00"
        case .blue:
            return "#0000FF"
        }
    }
}

let greenColor = Color.green

print(greenColor.hexValue)
// Output: #00FF00

在以上代码中,我们为 Color 枚举增加了一个计算属性 hexValue,用于表示颜色的十六进制值。

枚举中定义方法

Swift Code

enum Color {
    case red, green, blue

    func description() -> String {
        switch self {
        case .red:
            return "Color is red."
        case .green:
            return "Color is green."
        case .blue:
            return "Color is blue."
        }
    }
}

let greenColor = Color.green

print(greenColor.description())
// Output: Color is green.

在以上代码中,我们在 Color 枚举中添加了一个 description 方法,用于返回颜色的描述信息。

本文我们介绍了在 Swift 中如何定义枚举、遍历枚举、枚举原始值、枚举关联值等相关的内容。通过与 TypeScript 语法的对比,希望能帮助您更好地理解 Swift 的相关特性。


责任编辑:武晓燕 来源: 全栈修仙之路
相关推荐

2024-01-18 07:09:10

2019-11-12 08:53:32

PG数据数据库

2021-04-13 05:36:18

C#null 可控

2023-04-27 08:15:09

2020-11-17 08:07:29

存储类型浏览器

2023-12-06 14:23:24

2016-09-19 14:42:12

大数据SQLPig

2018-11-07 15:44:29

虚拟化服务器桌面

2021-02-27 17:13:21

前端代码逻辑

2021-10-12 09:20:02

数据库SQL脚本

2022-02-09 09:27:54

项目框架vue

2023-11-26 00:26:00

2019-05-10 11:13:19

分析工具Java

2023-05-30 14:54:17

Python循环语句工具

2023-05-29 09:41:42

2022-09-15 07:05:09

Windows电脑技巧

2021-11-04 11:54:30

Linux内存系统

2020-01-09 09:56:47

Java集合框架

2019-08-29 09:15:30

负载均衡算法备份

2024-03-01 13:48:00

Git配置系统
点赞
收藏

51CTO技术栈公众号