Search code examples
swiftprotocolsswift-protocols

How to create a Protocol in a Package without requiring Variables to be implemented Public?


Context

I have a Protocol, let's name it Entity, defined in a Swift Package. Since I want to use it in my projects, I set the Access Level to Public. However, Xcode is forcing me to set all Variables and Methods to Public as well, that were specified in the Protocol.

Compiler Error: Property 'name' must be declared public because it matches a requirement in public protocol 'Entity'


Code

// Swift Package
public protocol Entity {
    static var name: String
}

// Project
extension SomeEntity: Entity { // Compiler Error
    static var name: String = "Some Entity"
}

Question

  • How can I declare a Protocol in a Swift Package without requiring all Requirements to be made Public as well?

Solution

  • You cannot do that.

    If you make a type conform to a protocol, the conform will have the same access identifiers as the type itself. So if you make a public type conform to a protocol, the protocol conformance will be public as well.

    In order for a type to conform to a protocol, all protocol requirements must be met. And if you are able to refer to a type as the protocol it conforms to, you must be able to access all protocol requirements as well. So if you declare a type public and make it conform to a protocol, you must declare all protocol requirements (both properties and methods) as public.

    This is by design and you cannot get around it.