使用以下OptionSet:
struct StatusOptions : OptionSet {
let rawValue: Int
static let CountdownDuration0 = StatusOptions(rawValue: 1 << 0)
static let CountdownDuration1 = StatusOptions(rawValue: 1 << 1)
static let CountdownDuration2 = StatusOptions(rawValue: 1 << 2)
static let CountdownDuration3 = StatusOptions(rawValue: 1 << 3)
static let CountdownDuration4 = StatusOptions(rawValue: 1 << 4)
static let CountdownDuration5 = StatusOptions(rawValue: 1 << 5)
static let HomeMode = StatusOptions(rawValue: 1 << 6)
static let AwayMode = StatusOptions(rawValue: 1 << 7)
static let Disarmed: StatusOptions = []
static let ArmedHome: StatusOptions = .HomeMode
static let ArmedAway: StatusOptions = .AwayMode
static let ArmedBoth: StatusOptions = [.HomeMode, .AwayMode]
static let ArmingCountdown: StatusOptions = [.CountdownDuration0, .CountdownDuration1, .CountdownDuration2, .CountdownDuration3, .CountdownDuration4, .CountdownDuration5]
}
如何比较字节
var statusFlags: UInt8 = 0b00000000
选项?
以下是我认为可行的方法,但会导致操场错误:
if (statusFlags & .Disarmed) {
print("Disarmed")
}
由于
答案 0 :(得分:8)
由于.Disarmed
为零,您说:
if statusFlags == .Disarmed
甚至更简单:
if statusFlags.isEmpty
对于其他值,您说,例如:
if statusFlags.contains(.CountdownDuration3)
这是OptionSet的整个 point 。您使用 set 操作,而不是算术位操作。
但是为了使这个工作,你可以利用OptionSet的美味,statusFlags
需要 一个StatusOptions。您可以通过StatusOptions rawValue:
初始化程序来执行此操作:
let statusFlags = StatusOptions(rawValue:0b00000000)
statusFlags.isEmpty // true
(注意,在Swift 3中,可能甚至不会使用像.Disarmed
这样的零位掩码.Zone只是一个空集。)