Menu
CoddyTech

带关联值的枚举

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

Kotlin 密封层次结构可以表示多个带有不同负载的选项。Swift 关联值枚举可以直接表达这种结构:每个 case 都可以携带自己的值类型。switch 只有在匹配到对应 case 后才会绑定负载,从而避免使用只在某些状态下才有意义的可空字段。原始值枚举会将 case 映射到固定常量;关联值则是存储在每个特定枚举值中的数据。请根据领域选择合适的模型,而不是在无关字段旁添加序号或字符串标签。这个示例表示点或消息,并通过绑定每个 case 所携带的数据来格式化各自的结构。

Kotlin

sealed class Event {
    data class Point(val x: Int, val y: Int) : Event()
    data class Note(val text: String) : Event()
}
fun describe(e: Event): String = when (e) {
    is Event.Point -> "${e.x},${e.y}"
    is Event.Note -> e.text
}
fun main() { println(describe(Event.Point(2, 5))); println(describe(Event.Note("ready"))) }

Swift

enum Event { case point(Int, Int); case note(String) }
func describe(_ event: Event) -> String {
    switch event {
    case .point(let x, let y): return "\(x),\(y)"
    case .note(let text): return text
    }
}
print(describe(.point(2, 5)))
print(describe(.note("ready")))
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自我测试

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

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

自己练习: Swift 在线编辑器