-2

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 {
            
        }
    }


Developer-1
  • 163
  • 8
  • 1
    I don't understand the second part of your question, but in the first part you defined `all` incorrectly - it's now an `[Options]`, instead of `Options`. Did you mean for it to be `static let all: Options = [.option1, .option2, .option3]`? – New Dev May 07 '21 at 12:30
  • Yes, I made a mistake there without thinking of the consequences – Developer-1 May 07 '21 at 12:58

1 Answers1

1

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)
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52