带方法的枚举
本课属于 Coddy Swift 学习旅程的“面向对象编程”单元。第 15 课,共 57 课。
enum 用于定义一种类型,其中包含一组固定的情况。值前面加点号来书写,switch 必须处理每种情况,因此以后添加新情况时,所有需要更新的位置都会显示出来:
enum Direction {
case north, east, south, west
}
let heading = Direction.east
switch heading {
case .north: print("up")
case .east: print("right")
case .south: print("down")
case .west: print("left")
}输出:
right枚举可以有方法和计算属性。在枚举中,self 表示当前的枚举项:
enum Direction {
case north, east, south, west
var turnedRight: Direction {
switch self {
case .north: return .east
case .east: return .south
case .south: return .west
case .west: return .north
}
}
}
print(Direction.north.turnedRight)
print(Direction.west.turnedRight.turnedRight)输出:
east
east原始值会为每个枚举项关联一个固定类型的值。init(rawValue:)的作用相反,如果没有匹配的枚举项,就会返回nil:
enum Size: String {
case small = "S", medium = "M", large = "L"
}
print(Size.medium.rawValue)
print(Size(rawValue: "L") == .large)
print(Size(rawValue: "XL") == nil)输出:
M
true
true关联值让每个枚举情况都能携带自己的数据,因此一种类型可以包含形状各异的值。switch 使用 let 绑定数据:
enum Payment {
case cash(amount: Int)
case card(number: String, amount: Int)
var amount: Int {
switch self {
case .cash(let amount): return amount
case .card(_, let amount): return amount
}
}
}
let payments: [Payment] = [.cash(amount: 20), .card(number: "4242", amount: 55)]
print(payments.map { $0.amount })输出:
[20, 55]挑战
简单补全枚举 Command,添加 forward、back、left 和 right 这些成员,并分别使用原始值 F、B、L 和 R。添加一个计算属性 step,返回位置的变化量:前进为 1,后退为 -1,向左和向右为 0。然后补全 run(_:),将每个字符转换为命令(使用 init(rawValue:),跳过未知字符),并返回 position 2, turns 1, skipped 1。
提供的代码会读取一行命令字母,并输出 run(_:) 的结果。
你的代码应写在 Command.swift 和 Functions.swift 中。main.swift 包含提供的输入和输出代码,不能编辑。
亲手试试
// 提供的输入/输出代码:保持原样
var input: [String] = []
while let line = readLine() { input.append(line) }
print(run(input[0]))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
自己练习: Swift 在线编辑器