如何制作此 OptionSetType 结构 public?

How can I make this OptionSetType struct public?

我在自己的文件中定义了这个结构,想在其他地方和测试中使用它。

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

当我尝试使用它时,我得到一个关于如何无法声明 属性 的错误 public,因为该类型使用内部类型。

public var userPermissions = UserPermissions()

所以我想我可以做到 public,但这给了我一个关于需要 public 初始化函数的错误。

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

所以我将其添加到结构的定义中,这导致编译器崩溃:

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

一些访问控制的东西我还在思考Swift。我究竟做错了什么?如何使用此 OptionSetType?

如果您访问过 OptionSetType protocol reference 页面,您会找到所需的示例。您的 UserPermissions 是一个结构,没有要调用的 super

现在回答你的问题:

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]