【问题标题】:How do you perform a "~" (bitwise NOT) on a OptionSetType如何在 OptionSetType 上执行“~”(按位非)
【发布时间】:2015-08-11 19:09:30
【问题描述】:

在 Swift 1.2 之前,您可以在位掩码上执行 ~ (NOT):

bitmask = ~otherBitmask

但是在 Swift 2.0 中,位掩码现在是 OptionSetType,并且您不能在 OptionSetType 上使用 ~,那么您现在如何在 OptionSetType 上执行 ~ 操作?

【问题讨论】:

    标签: swift set swift2 bitmask


    【解决方案1】:

    您可以对原始值执行“按位非”。示例:

    let otherBitmask : NSCalendarOptions = [.MatchLast, .MatchNextTime]
    let bitmask = NSCalendarOptions(rawValue: ~otherBitmask.rawValue)
    

    如果你经常需要,你可以定义一个泛型 ~OptionSetType 的运算符:

    prefix func ~<T : OptionSetType where T.RawValue : BitwiseOperationsType>(rhs: T) -> T {
        return T(rawValue: ~rhs.rawValue)
    }
    
    let otherBitmask : NSCalendarOptions = [.MatchLast, .MatchNextTime]
    let bitmask = ~otherBitmask
    

    【讨论】:

    • 答案,但为了完全正确,我只想指出一件事:在我的特殊情况下,我使用的 OptionSetType (CGBitmapInfo.AlphaInfoMask) 是Uint32CGBitmapInfo.AlphaInfoMask.rawValue 是 '31',如果你是 ~31,你会得到 -32,但如果你是 ~CGBitmapInfo.AlphaInfoMask.rawValue,你会得到 4294967264。所以,为了完整起见,你需要确保将 UInt32 转换为 Int 之类的东西。
    • @Shizam:我不这么认为。 let otherBitmask : CGBitmapInfo = [.AlphaInfoMask] ; let bitmask = CGBitmapInfo(rawValue: ~otherBitmask.rawValue) 工作原理相同。
    猜你喜欢
    • 2015-11-13
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    相关资源
    最近更新 更多