Swift备忘

915 阅读1分钟

OptionSet

OptionSet作用类似于OC中按位枚举-NS_OPTIONS

  • 要存放枚举值,所以OptionSet遵循了RawRepresentable,提供了rawValue属性
  • 为了方便对rawValue进行位运算等操作,OptionSet要求rawValue必须遵循FixedWidthInteger(FixedWidthInteger的父protocol-BinaryInteger支持位运算)
  • OptionSet还遵循了SetAlgebra
    • 能够方便的进行集合操作
    • SetAlgebra继承的ExpressibleByArrayLiteral能够用arrayliteral的形式来给OptionSet赋值
struct ShippingOptions: OptionSet {
    let rawValue: Int

    static let nextDay    = ShippingOptions(rawValue: 1 << 0)
    static let secondDay  = ShippingOptions(rawValue: 1 << 1)
    static let priority   = ShippingOptions(rawValue: 1 << 2)
    static let standard   = ShippingOptions(rawValue: 1 << 3)

    static let express: ShippingOptions = [.nextDay, .secondDay]
    static let all: ShippingOptions = [.express, .priority, .standard]
}