Swift 枚举(下)

记录《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
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容