Encore en train de s'habituer à l'utilisation de OptionSetType
dans Swift.plus de test rapide idiomatique pour l'ensemble d'options?
En bon vieux C, si j'avais quelque chose comme
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;
je pouvais tester un ensemble de drapeaux avec quelque chose de simple comme:
if ((propertiesMask & (CHAR_PROP_NOTIFY | CHAR_PROP_INDICATE)) != 0) ...
L'alternative Swift pourrait ressembler
let properties:CBCharacteristicProperties = [.Write, .Read, .Indicate]
!properties.intersect([.Indicate, .Notify]).isEmpty
Existe-t-il une façon plus idiomatique de faire ce test? Pas un fan de la! à l'avant. Mais sinon, semble assez simple, sauf que je suis vraiment intéressé quand il y a une intersection. Cela m'a amené à vouloir ajouter le mien.
extension OptionSetType {
func hasIntersection(other:Self) -> Bool {
return !self.intersect(other).isEmpty
}
}
Ce qui me permet alors d'écrire
properties.hasIntersection([.Indicate, .Notify])
est-il un moyen de mieux/plus idiomatiques de le faire? Ai-je roulé le mien et ai-je manqué quelque chose?
Pour éviter le '!', Vous pouvez faire 'prope rties.intersect ([. Indiquer, .Notifier]). count> 0' – sschale