Correct value of rawValue in an OptionSet?

47 views Asked by At

When working with an OptionSet, I believed that the rawValue always represented the combination of bits. In the example below, the "all" value does not have a correct rawValue. It is zero.

If placing a breakpoint in the init function, it will indeed get hit with a 0 value when initialising the "all" option set.

struct Options: OptionSet {

    init(rawValue: Int16) {
        self.rawValue = rawValue
    }
    
    let rawValue: Int16

    static let option1 = Options(rawValue:1)
    static let option2 = Options(rawValue:2)
    static let option3 = Options(rawValue:4)

    static let all = [option1,option2,option3]
}

To do something constructive, I have implemented the special init function that conforms to the ExpressibleByArrayLiteral protocol. But to no avail, as it is not called, when used in a static initialisation (however it will get called when used in a non-static initialisation).

struct Options: OptionSet {
...

    public init(arrayLiteral: Element...) {
        for element in arrayLiteral {
            
        }
    }


1

There are 1 answers

0
Joakim Danielson On BEST ANSWER

You need to declare all to be of type Options

static let all: Options = [option1,option2,option3]

Example

print(Options.all) // prints Options(rawValue: 7)