根据NSHipster的this article,我想使用以下方法创建一个允许使用位掩码的枚举:
struct Toppings : RawOptionSetType, BooleanType {
private var value: UInt = 0
init(_ value: UInt) {
self.value = value
}
// MARK: RawOptionSetType
static func fromMask(raw: UInt) -> Toppings {
return self(raw)
}
// MARK: RawRepresentable
static func fromRaw(raw: UInt) -> Toppings? {
return self(raw)
}
func toRaw() -> UInt {
return value
}
// MARK: BooleanType
var boolValue: Bool {
return value != 0
}
// MARK: BitwiseOperationsType
static var allZeros: Toppings {
return self(0)
}
// MARK: NilLiteralConvertible
static func convertFromNilLiteral() -> Toppings {
return self(0)
}
// MARK: -
static var None: Toppings { return self(0b0000) }
static var ExtraCheese: Toppings { return self(0b0001) }
static var Pepperoni: Toppings { return self(0b0010) }
static var GreenPepper: Toppings { return self(0b0100) }
static var Pineapple: Toppings { return self(0b1000) } }
它引发了以下四个错误:
Initializer 'init' has different argument names from those required by protocol 'RawRepresentable' ('init(rawValue:)')
Type 'Toppings' does not conform to protocol 'RawRepresentable'
Type 'Toppings' does not conform to protocol 'Equatable'
Type 'Toppings' does not conform to protocol 'NilLiteralConvertible'
我设法通过实施Equatable
来解决func ==(lhs: Self, rhs: Self) -> Bool
错误。但似乎没有认识到这个功能。
是否有解决方案来解决上述所有错误?我比toRaw()
更喜欢这个解决方案。所以,如果可以解决上面的代码,我非常感兴趣。
答案 0 :(得分:2)
要符合NilLiteralConvertible
添加其他初始化程序并将结构初始化为nil
值:
init(nilLiteral: ()) { }
符合RawRepresentable
:
typealias RawValue = UInt
var rawValue: RawValue {
get {
return value
}
}
init(rawValue value: UInt) {
self.value = value
}
当您需要了解如何符合特定协议时,在Xcode中, cmd + 单击协议名称上的。