更多惯用的快速测试选项集?

时间:2016-05-25 21:40:32

标签: swift optionsettype

仍然习惯在Swift中使用OptionSetType

好的' C,如果我有类似

的东西
typedef enum {
    CHAR_PROP_BROADCAST          =0x01,
    CHAR_PROP_READ               =0x02,
    CHAR_PROP_WRITE_WITHOUT_RESP =0x04,
    CHAR_PROP_WRITE              =0x08,
    CHAR_PROP_NOTIFY             =0x10,
    CHAR_PROP_INDICATE           =0x20,
    CHAR_PROP_SIGNED_WRITE       =0x40,
    CHAR_PROP_EXT                =0x80
} CharacteristicProperty;

我可以用简单的东西来测试一组标志:

if ((propertiesMask & (CHAR_PROP_NOTIFY | CHAR_PROP_INDICATE)) != 0) ...

Swift替代品可能看起来像

let properties:CBCharacteristicProperties = [.Write, .Read, .Indicate]
!properties.intersect([.Indicate, .Notify]).isEmpty

是否有更惯用的方法来进行此测试?不是粉丝!在前面。但除此之外,似乎很简单,除非我对交叉点感兴趣。这导致我想要添加自己的。

extension OptionSetType {
    func hasIntersection(other:Self) -> Bool {
        return !self.intersect(other).isEmpty
    }
}

然后允许我写

properties.hasIntersection([.Indicate, .Notify])

有更好/更惯用的方法吗?我是不是自己动手而错过了什么?

2 个答案:

答案 0 :(得分:1)

SetAlgebraType实现的协议OptionSetType中有这种方法:

  

isDisjointWith(_: Self) -> Bool

     

返回true iff self.intersect(other).isEmpty。

所以你可以将你的考试缩短为:

!properties.isDisjointWith([.Indicate, .Notify])

properties.isDisjointWith([.Indicate, .Notify]) == false

您还可以将原始值与按位运算符进行比较,就像在C:

中一样
(properties.rawValue & (CharacteristicProperties.Notify.rawValue | CharacteristicProperties.Indicate.rawValue)) != 0

完整示例代码(在游乐场中):

struct CBCharacteristicProperties : OptionSetType {
  let rawValue: UInt
  init(rawValue: UInt) { self.rawValue = rawValue }

  static let Broadcast          = CBCharacteristicProperties(rawValue:0x01)
  static let Read               = CBCharacteristicProperties(rawValue:0x02)
  static let WriteWithoutResp   = CBCharacteristicProperties(rawValue:0x04)
  static let Write              = CBCharacteristicProperties(rawValue:0x08)
  static let Notify             = CBCharacteristicProperties(rawValue:0x10)
  static let Indicate           = CBCharacteristicProperties(rawValue:0x20)
  static let SignedWrite        = CBCharacteristicProperties(rawValue:0x40)
  static let Ext                = CBCharacteristicProperties(rawValue:0x80)
}

let properties = CBCharacteristicProperties([.Write, .Read, .Indicate])
print(!properties.intersect([.Indicate, .Notify]).isEmpty)
print(!properties.isDisjointWith([.Indicate, .Notify]))
print(properties.isDisjointWith([.Indicate, .Notify]) == false)
print((properties.rawValue & (CBCharacteristicProperties.Notify.rawValue | CBCharacteristicProperties.Indicate.rawValue)) != 0)

结果:

"true"
"true"
"true"
"true"

答案 1 :(得分:0)

我发现最有吸引力的实际解决方案是简单地添加以下扩展名:

extension SetAlgebraType {
    var notEmpty:Bool {
        return self.isEmpty.NOT
    }
}

这让我可以编写代码:

if properties.intersect([.Indicate, .Notify]).notEmpty {
    ...
}