swift 使用OptionSet的便捷方法是什么?

5us2dqdw  于 2023-06-28  发布在  Swift
关注(0)|答案(2)|浏览(208)

我在一个项目中使用了许多按位选项集,每个选项集都包含许多带有all选项的选项,例如:

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

它需要维护许多类似的代码,所以有没有办法消除硬编码的按位移位操作和all选项?

ecfdbz9o

ecfdbz9o1#

你可以使用next OptionSet的扩展,它实现了all选项和一个方便的初始化器:

  1. extension OptionSet where RawValue == Int {
  2. static var all: Self {
  3. Self.init(rawValue: Int.max)
  4. }
  5. init(_ shift: Int) {
  6. self.init(rawValue: 1 << shift)
  7. }
  8. }

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

  1. struct Option: OptionSet {
  2. let rawValue: Int
  3. static let a = Self(0)
  4. static let b = Self(1)
  5. static let c = Self(2)
  6. }
  7. Option.a.rawValue // 1
  8. Option.b.rawValue // 2
  9. Option.c.rawValue // 4
  10. let options: Option = [.a, .b]
  11. Option.all.contains(options) // true
展开查看全部
gev0vcfq

gev0vcfq2#

辅助程序库Options正是您所需要的;)

相关问题