问题描述
如果声明这样的枚举可以正常工作,但是共同尝试使用OR 2值无法编译: p>
枚举MyEnum:Int
{
case One = 0x01
case Two = 0x02
案例四= 0x04
案例八= 0x08
}
//按照预期的方式工作
let m1:MyEnum = .One
//编译器错误:无法找到接受提供的参数的'|'的重载
let combined:MyEnum = MyEnum.One | MyEnum.Four
我看了一下Swift如何导入基础枚举类型,它通过定义一个 struct
符合 RawOptionSet
协议:
struct NSCalendarUnit:RawOptionSet {
init(_ value:UInt)
var value:UInt
static var CalendarUnitEra:NSCalendarUnit {get}
static var CalendarUnitYear :NSCalendarUnit {get}
// ...
}
RawOptionSet
协议是:
协议RawOptionSet:LogicValue,Equable {
类func fromMask(raw:Self.RawType) - >自我
}
然而,这个协议没有文档,我不能如何实现它自己。此外,还不清楚这是否是Swift官方实施位字段的方法,或者这只是Objective-C桥如何代表它们。
您可以构建符合 RawOptionSet
协议的 struct
,您将可以使用它像内置的枚举
类型,但与位掩码功能一样。这里的答案显示如何:
。
How should bit fields be declared and used in Swift?
Declaring an enum like this does work, but trying to OR 2 values together fails to compile:
enum MyEnum: Int
{
case One = 0x01
case Two = 0x02
case Four = 0x04
case Eight = 0x08
}
// This works as expected
let m1: MyEnum = .One
// Compiler error: "Could not find an overload for '|' that accepts the supplied arguments"
let combined: MyEnum = MyEnum.One | MyEnum.Four
I looked at how Swift imports Foundation enum types, and it does so by defining a struct
that conforms to the RawOptionSet
protocol:
struct NSCalendarUnit : RawOptionSet {
init(_ value: UInt)
var value: UInt
static var CalendarUnitEra: NSCalendarUnit { get }
static var CalendarUnitYear: NSCalendarUnit { get }
// ...
}
And the RawOptionSet
protocol is:
protocol RawOptionSet : LogicValue, Equatable {
class func fromMask(raw: Self.RawType) -> Self
}
However, there is no documentation on this protocol and I can't figure out how to implement it myself. Moreover, it's not clear if this is the official Swift way of implementing bit fields or if this is only how the Objective-C bridge represents them.
You can build a struct
that conforms to the RawOptionSet
protocol, and you'll be able to use it like the built-in enum
type but with bitmask functionality as well. The answer here shows how:Swift NS_OPTIONS-style bitmask enumerations.
这篇关于在Swift中声明并使用位域枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!