Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I allowed method access less restrictive than class access?

Tags:

swift

Why does this compile?

internal class A {

    public func f() {

    }
}

I expected f's "public" modifier to be disallowed because its enclosing class is internal.

like image 308
Ian Warburton Avatar asked Oct 27 '16 16:10

Ian Warburton


1 Answers

One motivation for allowing this is mentioned in SE-0025: Scoped Access Level (emphasis mine):

The compiler should not warn when a broader level of access control is used within a type with more restrictive access, such as internal within a private type. This allows the owner of the type to design the access they would use were they to make the type more widely accessible. (The members still cannot be accessed outside the enclosing lexical scope because the type itself is still restricted, i.e. outside code will never encounter a value of that type.)

So, although it doesn't change the accessibility of the members, it allows developers to communicate the access level they feel a given member should have if the enclosing type had a broader access level – which could for example be useful for APIs that currently have internal types which are planned to be made public in a future release.

like image 173
Hamish Avatar answered Nov 19 '22 23:11

Hamish