Swift Enums 使用枚举的另一些实践和功能

本篇内容将记录一些使用枚举的实践和功能,按惯例会附上示例代码、优缺点等。

Swift 中的枚举 enumerations 是一种多功能且强大的功能,它可以增强代码的可读性、可维护性和类型安全性,它提供了定义一组相关值通用类型的方式,能够在代码中以类型安全的方式使用这些值。


什么是 Swift 枚举?

枚举(enumerations),也称为枚举类型(enums),用于以类型安全的方式处理一组相关值。每个枚举定义了一组相关值的通用类型,并使您能够在代码中以类型安全的方式使用这些值。

枚举的使用

  • 使用枚举来表示预定义的一组状态或类别,例如星期几、状态机中的状态或应用程序中的模式。
  • 枚举与 switch 语句搭配使用效果很好,可以实现详尽的检查并减少错误。
  • 枚举提供类型安全性,可以防止使用无效值。
  • 避免在需要复杂数据结构的情况下使用枚举,此时使用类或结构体会更合适。
  • 枚举他并不适合表示需要随着时间变化的数据。这时可以改用类或结构体。
  • 如果值的集合预计会频繁变化或者会无限增长,那么不建议使用枚举。

基本用法:

enum WeekDay {
    case monday
    case tuesday
    case wednesday
    case thursday
    case friday
    case saturday
    case sunday
    // 或者这样定义
    // case monday, tuesday, wednesday, thursday, friday, saturday, sunday
}

枚举页可以存储特定类型的原始值,使其在表示已知值时非常好用,比如定义网络接口状态码。

enum ResponseCode: Int {
    case ok = 200
    case forbiden = 401
    case notfound = 404
    case failed = 500
}

也可以存储任意类型的关联值,为每个枚举案例存储额外的数据。

enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

也可以为枚举添加方法,这样使用枚举会有更好的表现。

enum Planet: String {
    case mercury, venus, earth, mars
    
    func description() -> String {
        switch self {
        case .mercury: return "水星是离太阳最近的行星。"
        case .venus: return "金星是第二颗离太阳最近的行星。"
        case .earth: return "地球是我们的家园。"
        case .mars: return "火星被称为红色星球。"
        }
    }
}

支持的功能


枚举可以具有计算属性,这样枚举可以提供派生值,那么使用更加灵活。

enum Device {
    case iPhone(model: String)
    case iPad(model: String)
    
    var description: String {
        switch self {
        case .iPhone(let model): return "iPhone 型号:\(model)"
        case .iPad(let model): return "iPad 型号:\(model)"
        }
    }
}

同时,枚举它还可以递归,这样可以将另一个枚举的实例作为关联值。

indirect enum ArithmeticExpression {
    case number(Int)
    case addition(ArithmeticExpression, ArithmeticExpression)
    case multiplication(ArithmeticExpression, ArithmeticExpression)
}

另外,想要控制枚举的初始化过程,可以自定义初始化枚举

enum Color {
    case rgb(red: Int, green: Int, blue: Int)
    
    init(white: Int) {
        self = .rgb(red: white, green: white, blue: white)
    }
}

使用示例

定义系统主题模式

enum AppTheme {
    case light, dark, system
    
    var description: String {
        switch self {
        case .light: return "浅色模式"
        case .dark: return "深色模式"
        case .system: return "系统默认"
        }
    }
}

定义网络请求结果

enum Result<T> {
    case success(T)
    case failure(Error)
}

枚举默认值和失败处理

enum ResponseCode: Int {
    case ok = 200
    case notfound = 404
    
    init?(rawValue: Int) {
        switch rawValue {
        case 200: self = .ok
        case 404: self = .notfound
        default: return 999
        }
    }
}

具有相似行为时使用协议

protocol Animal {
    func sound() -> String
}

enum DogBreed: Animal {
    case labrador, beagle
    
    func sound() -> String {
        return "汪汪汪"
    }
}

enum CatBreed: Animal {
    case persian, siamese
    
    func sound() -> String {
        return "喵喵喵"
    }
}

需要共享行为的枚举可以使用静态方法

enum PaymentStatus {
    case pending, completed, failed
    
    static func processPayment(for status: PaymentStatus) -> String {
        switch status {
        case .pending: return "付款待处理。"
        case .completed: return "付款已完成。"
        case .failed: return "付款失败。"
        }
    }
}

  本文自 https://www.codeun.com 发布,相应代码均自主编写并严格审阅和测试,完整代码中包含丰富的学习笔记和使用方式、实用技巧。
  · 如若转载,请注明出处:https://www.codeun.com/archives/1321.html ·

(0)
上一篇 2024-06-20
下一篇 2024-10-05

发表回复

登录后才能评论