首页 > 解决方案 > 使用 OptionSet 的便捷方式是什么?

问题描述

我在一个具有许多按位选项集的项目上工作,每个选项集都包含许多带有选项的all选项,例如:

struct MyOption: OptionSet {
    let rawValue: Int
    
    static let a = Self(rawValue: 1 << 0)
    static let b = Self(rawValue: 1 << 1)
    static let c = Self(rawValue: 1 << 2)
    ...
    static let last = Self(rawValue: 1 << N)
    
    static let all: Self = [.a, .b, .c, ..., .last]
}

它需要维护许多类似的代码,那么有什么方法可以消除硬编码的按位移位操作和all选项?

标签: swiftoptionsettypeoption-set

解决方案


您可以使用 nextOptionSet的扩展来实现all选项和方便的初始化程序:

extension OptionSet where RawValue == Int {
    static var all: Self {
        Self.init(rawValue: Int.max)
    }
    
    init(_ shift: Int) {
        self.init(rawValue: 1 << shift)
    }
}

然后你可以重写你的选项集:

struct Option: OptionSet {
    let rawValue: Int
    
    static let a = Self(0)
    static let b = Self(1)
    static let c = Self(2)
}

Option.a.rawValue // 1
Option.b.rawValue // 2
Option.c.rawValue // 4

let options: Option = [.a, .b]
Option.all.contains(options) // true

推荐阅读