记录《objccn-advanced-swift》
在枚举和协议之间的相似
一个画图程序
enum Shape {
case line(from: Point, to: Point)
case rectangle(origin: Point, width: Double, height: Double) case circle(center: Point, radius: Double)
}
extension Shape {
func render(into context: CGContext) {
switch self {
case let .line(from, to): // ...
case let .rectangle(origin, width, height): // ...
case let .circle(center, radius): // ...
} }
}
protocol Shape {
func render(into context: CGContext)
}
struct Rectangle: Shape {
var origin: Point
var width: Double
var height: Double
func render(into context: CGContext) { /* ... */ } }
在枚举中可以轻松添加新的渲染方法,而协议可以轻松地添加新的形状
使用枚举实现递归数据结构
/// 一个单向链表。
enum List<Element> {
case end
indirect case node(Element, next: List<Element>)
}
原始值
enum HTTPStatus: Int {
case ok = 200
case created = 201
// ...
case movedPermanently = 301 // ...
case notFound = 404
// ...
}
列举枚举值
protocol CaseIterable {
associatedtype AllCases: Collection where AllCases.Element == Self
static var allCases: AllCases { get }
}
固定和非固定枚举
@frozen enum Optional<Wrapped> {
case some(Wrapped)
case none
}