Public OptionSet with a private constructor

I have some example code:

public struct MyOptions: OptionSet {
    public let rawValue: Int

    public init(rawValue: Int) {
        self.rawValue = rawValue
    }

    public static let one = MyOptions(rawValue: 1 << 0)
    public static let two = MyOptions(rawValue: 1 << 1)
}

      

In another module, I can do:

print(MyOptions.one)
print(MyOptions(rawValue: 10))

      

How can I create a public structure with a private constructor and public static properties (like one, two) to restrict manual creation?

+4


source to share


1 answer


You Can't. When you negotiate a type with a protocol, all required stub protection levels must be at least equal to the type's protection level. I will try to explain why.

Let's say I have a type Foo

that I match Hashable

. Then I assign the instance as a type Hashable

:

let foo: Hashable = Foo()

      



Since the instance is of a type Hashable

, I am guaranteed to have access to the method hash(into:)

. But what if I make the method private? At this point, you will get unexpected behavior. Either for some reason I cannot access a method that I had guaranteed access to, or I have access to a method that I should not have access to. This is a conflict of access levels.

So yes, what you want to do is not possible.

0


source







All Articles