RawOptionsSetType 在 Xcode6 中的 Swift 中引发错误

RawOptionsSetType raises error in Swift in Xcode6

根据 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'

我通过实施 func ==(lhs: Self, rhs: Self) -> Bool 设法解决了 Equatable 错误。但是好像识别不了这个功能

是否有解决上述所有错误的方法?与 toRaw() 相比,我更喜欢此解决方案。所以我非常想知道上面的代码是否可以修复。

为了符合 NilLiteralConvertible 添加另一个初始化程序并将您的结构初始化为其 nil 值:

init(nilLiteral: ()) { }

符合RawRepresentable:

typealias RawValue = UInt

var rawValue: RawValue {
    get {
        return value
    }
}

init(rawValue value: UInt) {
    self.value = value
}

当你需要了解如何符合特定的协议时,在Xcode、cmd+点击上协议名称。