2016-09-30 82 views
3

用下面OptionSet:雨燕3.0 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") 
} 

感謝

回答

6

由於.Disarmed是零,你說:

if statusFlags == .Disarmed 

甚至更簡單:

if statusFlags.isEmpty 

對於其他值,你說的,例如:

if statusFlags.contains(.CountdownDuration3) 

這是一個OptionSet全。您使用集合操作,而不是算術位操作。

但是這個工作,這樣就可以充分利用OptionSet的美味良善,statusFlags需要一個StatusOptions。你可以做到這一點的StatusOptions方式rawValue:初始化:

let statusFlags = StatusOptions(rawValue:0b00000000) 
statusFlags.isEmpty // true 

(注意,在斯威夫特3,零位掩碼像.Disarmed可能甚至不會使用零隻是一個空集。)