如何在 OptionSetType 上执行“~”(按位非)

How do you perform a "~" (bitwise NOT) on a OptionSetType

直到 Swift 1.2 你可以在位掩码上执行 ~ (NOT):

bitmask = ~otherBitmask

但是在 Swift 中,2.0 位掩码现在是 OptionSetType,你不能在 OptionSetType 上使用 ~,你现在如何做 ~ 操作 OptionSetType?

您可以对原始值执行 "bitwise NOT"。示例:

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