Access level of members defined in an extension

(Martin R) #1

I have a question about the relationship between the access level of an extension
and the access level of members defined in that extension.

The "Access Control" chapter in "The Swift Programming Language" states about extensions:

   Alternatively, you can mark an extension with an explicit access-level modifier
   (for example, private extension) to set a new default access level for all members
   defined within the extension. This new default can still be overridden within the
   extension for individual type members.
But apparently the access level of a member can only be equal to or lower than the
access of the extension in which it is defined, and the compiler warns if I try to
increase it:

    private class MyClass {
        public func foo() { } // No warning

    private extension MyClass {
        public func bar() { } // warning: declaring a public instance method in a private extension

There is no warning for `func foo` which is defined in the class itself, only for
`func bar` which is defined in an extension.

SE-0117 states that

   ... the true access level of a type member is computed as the minimum of the true
   access level of the type and the declared access level of the member.

My questions are:

- Does a similar statement hold for members defined in an extension, i.e. the true
  access level is the minimum of the declared access level and the access level of
  the extension in which it is defined? In other words, I can only lower the default
  access level of the extension, but not increase it.
- Why does the compiler warn if I define a member with a higher access level in an
  extension, but not if I do the same in the main class definition?