gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:42:53 25 4
gpt4 key购买 nike

仍然习惯在 Swift 中使用 OptionSetType

在好的 ol' 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])

是否有更好/更惯用的方法来做到这一点?我是不是自己滚而错过了什么?

最佳答案

OptionSetType 实现的协议(protocol) SetAlgebraType 中有这个方法:

isDisjointWith(_: Self) -> Bool

Returns 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

完整示例代码(在 playground 中):

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"

关于swift - 选项集更惯用的快速测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37448077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com