Menu
CoddyTech

带有关联值的枚举

Coddy 面向 C 开发者的 Swift 课程的第 40 课,共 48 课。

带标签的 C 联合体使用单独的判别字段和重叠的载荷存储空间,由程序逻辑维护哪个成员有意义。Swift 关联值枚举会在类型系统中将每个枚举项与其声明的载荷形状绑定。每个值选择一个枚举项,并携带该枚举项的数据。

源工厂函数会同时初始化 retry 标签和 seconds 成员,然后由 switch 读取相应的载荷。Swift 匹配 .retry,并直接绑定其关联的 seconds 值。同一个枚举项的不同值可以携带不同数据,这与枚举项的原始值不同。

C:完整程序

download.h

#ifndef DOWNLOAD_H
#define DOWNLOAD_H
typedef enum { DOWNLOAD_READY, DOWNLOAD_RETRY } DownloadKind;
typedef struct { DownloadKind kind; union { const char *path; int seconds; } data; } Download;
#endif

ready.h

#ifndef READY_H
#define READY_H
#include "download.h"
static inline Download ready(const char *path) { Download value = {.kind=DOWNLOAD_READY, .data.path=path}; return value; }
#endif

retry.h

#ifndef RETRY_H
#define RETRY_H
#include "download.h"
static inline Download retry(int seconds) { Download value = {.kind=DOWNLOAD_RETRY, .data.seconds=seconds}; return value; }
#endif

main.c

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "ready.h"
#include "retry.h"

int main(void) {
Download outcome = retry(4);
    switch (outcome.kind) {
        case DOWNLOAD_READY: puts(outcome.data.path); break;
        case DOWNLOAD_RETRY: printf("retry %d\n", outcome.data.seconds); break;
    }
    return 0;
}

Swift:完整程序

Download.swift

import Foundation
enum Download {
    case ready(path: String)
    case retry(seconds: Int)
}

main.swift

import Foundation
let outcome: Download = .retry(seconds: 4)
switch outcome {
case .ready(let path): print(path)
case .retry(let seconds): print("retry \(seconds)")
}

不要忽略 C 标签,直接读取任意联合体成员。Swift 模式匹配为预期的不同选项提供了更安全、直接的表示方式。

challenge icon

挑战

简单

实现 Ticket 枚举,包含 day(Int) 和 bundle(Int, Int) 两种情况。其 cost: Int 等于日票价格,或套票数量乘以单价。输入为 day price 或 bundle quantity price;数字字段的范围为 0 到 100。输出费用。

实现所需的 API 和 solve(_ input: String) -> String。返回不带末尾换行符的输出文本;不要在可编辑代码中打印内容。锁定的驱动程序会使用其他有效输入独立检查这些 API,然后将返回的文本连同且仅连同一个换行符一起打印。所有数值运算都不会超出 Int 的范围。

你的代码应写在 Ticket.swift 和 Functions.swift 中。main.swift 包含提供的输入/输出代码,不能编辑。

亲手试试

import Foundation
func apiChecks(_ input: String) -> Bool {
return Ticket.day(11).cost == 11 && Ticket.bundle(4, 7).cost == 28 && Ticket.bundle(0, 9).cost == 0
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 开始公开 API 检查
let apiOK = apiChecks(input)
// 结束公开 API 检查
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C 开发者的 Swift中的所有课

自己练习: Swift 在线编辑器