Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

public OptionSet with private constructor

Tags:

swift

I have a sample 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 other module I can do:

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

How can I do public struct with private constructor and public static properties(like a one, two) to limit manual creation?

like image 455
qRoC Avatar asked May 04 '17 06:05

qRoC


1 Answers

You can't. When you conform a type to a protocol, all the required stubs' protection levels must be at least equal to the type's protection level. I'll try to explain why.

Let's say I have a type Foo that I conform to Hashable. I then assign an instance as a Hashable type:

let foo: Hashable = Foo()

Because the instance is of type Hashable, I am guaranteed to have access to the hash(into:) method. But what if I make the method private? At that point you end up with unexpected behavior. Either for some reason I can't access a method that I was guaranteed access to, or I have access to a method that I shouldn't be able to reach. It's a conflict of access levels.

So yeah, what you want to do isn't possible.

like image 144
Caleb Kleveter Avatar answered Oct 24 '22 03:10

Caleb Kleveter