Search code examples
swiftcompiler-errorsprotocolsaccess-modifiers

Swift - 'internal' modifier cannot be used in protocols


I am getting compiler error when I am declaring function internal inside Swift protocol,

protocol MyProtocol {
    internal func test()
}

Error:

'internal' modifier cannot be used in protocols

Error is resolved if I remove the access modifier internal but I want to know why I am getting this error? As documentation mentioned default access level will be internal in case if I do not explicitly mention any access level. So why it is producing comilers error when I am making it explicit.


Solution

  • Please scroll down in the linked article

    Protocols

    If you want to assign an explicit access level to a protocol type, do so at the point that you define the protocol. This enables you to create protocols that can only be adopted within a certain access context.

    The access level of each requirement within a protocol definition is automatically set to the same access level as the protocol. You can’t set a protocol requirement to a different access level than the protocol it supports. This ensures that all of the protocol’s requirements will be visible on any type that adopts the protocol.

    It means you have to declare

    internal protocol MyProtocol {
         func test()
    }