swift - 使用 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
选项?
解决方案
您可以使用 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
推荐阅读
- r - 有没有一种快速的方法可以将数据表转换为数据表列表?
- azure - 试图找到与 New-AzureADGroupAppRoleAssignment 等效的 Azure CLI
- asp.net - 如何在默认的 asp .net 3.1 剃须刀模板中添加下拉菜单
- python - 如何更好地实现缩放图像?
- python - 如何在单击地图后抓取数据仅显示在绘图中的 Tableau 仪表板?
- tensorflow - 神经网络输入形状
- python - 如何让 askopenfilenames 遍历用户输入?
- java - 线程“main”java.lang.NumberFormatException 中的异常:对于输入字符串:基数 16 下的“9000000000000000”
- java - 如何通过命令行在某个阶段执行某些配置的maven插件?
- aws-lambda - 使用 lambda 函数在不同区域触发 SES