1.7 · Access control

Access control is API design enforced by the compiler. The interesting levels are not private — they are package, public, and open, which decide what a binary can promise to the outside world.

Mental model. Pick the narrowest level that still lets the code that needs it compile. Widening later is easy; narrowing is a breaking change.

The access levels

Who can see a declaration.

  1. What is the purpose of access control? List the levels. 1.7.1 · L1
    Access control limits who can depend on a declaration — it is how you keep an API small while keeping implementation details free to change. private — the…
  2. public vs open? Can a struct be open? 1.7.2 · L2
    open is for classes and class members that may be subclassed or overridden outside the module. public is visible to importers but closed to inheritance from…

Modules and packages

Boundaries bigger than a file.

  1. What does package access solve? 1.7.3 · L3
    In an SPM package with many targets, internal is per target. Shared helpers therefore had to be public, leaking them to everyone who imported the package.…
  2. What are @usableFromInline and @inlinable in relation to access control? 1.7.4 · L5
    @inlinable puts a function's body into the client's module so it can be specialized and inlined across module boundaries. The body may only reference public or…

More in Swift language