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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With