You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否用纯布尔逻辑替换位掩码包装器Setter中的if/else语句?

问题:能否用纯布尔逻辑替换-setActionNotificationPacketReceived:中的if/else语句?

先看现有代码实现:

.h文件代码

typedef NS_OPTIONS(NSUInteger, ActionTrigger) {
    bitmask0            = 1 << 0,
    bitmask1            = 1 << 1,
    ...
};
@property (nonatomic) ActionTrigger notificationTrigger;
@property (nonatomic) BOOL actionNotificationPacketReceived;

.m文件代码

- (BOOL)actionNotificationPacketReceived    {
    return ((self.notificationTrigger   & bitmask0) == bitmask0);
}

- (void)setActionNotificationPacketReceived:(BOOL)value {
    if (value) {
        self.notificationTrigger |= bitmask0;
    } else {
        self.notificationTrigger &= ~bitmask0;
    }
}

纯布尔逻辑替换方案

可以通过位运算组合直接实现,不需要if/else判断:

- (void)setActionNotificationPacketReceived:(BOOL)value {
    // 先清除bitmask0对应位,再根据value决定是否设置该位
    self.notificationTrigger = (self.notificationTrigger & ~bitmask0) | (value ? bitmask0 : 0);
}

或者利用OC中BOOL本质为整数的特性进一步简化:

- (void)setActionNotificationPacketReceived:(BOOL)value {
    NSUInteger targetBit = (NSUInteger)value * bitmask0;
    self.notificationTrigger = (self.notificationTrigger & ~bitmask0) | targetBit;
}

编辑补充
最终我使用了如下宏封装该逻辑:

#define OptionSetBool(option, flag, a_bool) ((a_bool) ? ((option) |= flag) : ((option) &= ~flag))

内容的提问来源于stack exchange,提问作者Mojo66

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 10:15:33