swiftstructaccess-controloptionsettype

How can I make this OptionSetType struct public?


I have this struct defined in its own file and want to use it elsewhere and in testing.

struct UserPermissions : OptionSetType {
    let rawValue: UInt
    static let CreateFullAccount = UserPermissions(rawValue: 1 << 1)
    static let CreateCustomAccount = UserPermissions(rawValue: 1 << 2)
}

When I try to use it I get an error about how the property cannot be declared public because the type uses an internal type.

public var userPermissions = UserPermissions()

So I thought I could make it public, but that gives me an error about needing a public init function.

public struct UserPermissions : OptionSetType {
    public let rawValue: UInt
    static let CreateFullAccount = UserPermissions(rawValue: 1 << 1)
    static let CreateCustomAccount = UserPermissions(rawValue: 1 << 2)
}

So I add this to the definition of the struct, which causes the compiler to crash:

public init(rawValue: Self.RawValue) {
    super.init(rawValue)
}

Some of the access control stuff I'm still wrapping my head around in Swift. What am I doing wrong? How can I use this OptionSetType?


Solution

  • Had you visited the OptionSetType protocol reference page, you would have found an example of what you need. Your UserPermissions is a struct, there's no super to be called.

    Now to answer your question:

    public struct UserPermissions : OptionSetType {
        public let rawValue: UInt
        public init(rawValue: UInt) { self.rawValue = rawValue }
    
        static let CreateFullAccount = UserPermissions(rawValue: 1 << 1)
        static let CreateCustomAccount = UserPermissions(rawValue: 1 << 2)
    }
    
    // Usage:
    let permissions: UserPermissions = [.CreateFullAccount, .CreateCustomAccount]