【发布时间】:2015-08-11 19:09:30
【问题描述】:
在 Swift 1.2 之前,您可以在位掩码上执行 ~ (NOT):
bitmask = ~otherBitmask
但是在 Swift 2.0 中,位掩码现在是 OptionSetType,并且您不能在 OptionSetType 上使用 ~,那么您现在如何在 OptionSetType 上执行 ~ 操作?
【问题讨论】:
在 Swift 1.2 之前,您可以在位掩码上执行 ~ (NOT):
bitmask = ~otherBitmask
但是在 Swift 2.0 中,位掩码现在是 OptionSetType,并且您不能在 OptionSetType 上使用 ~,那么您现在如何在 OptionSetType 上执行 ~ 操作?
【问题讨论】:
您可以对原始值执行“按位非”。示例:
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) 是Uint32。 CGBitmapInfo.AlphaInfoMask.rawValue 是 '31',如果你是 ~31,你会得到 -32,但如果你是 ~CGBitmapInfo.AlphaInfoMask.rawValue,你会得到 4294967264。所以,为了完整起见,你需要确保将 UInt32 转换为 Int 之类的东西。
let otherBitmask : CGBitmapInfo = [.AlphaInfoMask] ; let bitmask = CGBitmapInfo(rawValue: ~otherBitmask.rawValue) 工作原理相同。