Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 146 ยท Structures, Classes and Enums

Access Control

Learn Swift access control - private, fileprivate, internal, package, public and open, private(set), access in extensions, and how modules decide who can see your code, with real compiler errors.

Good code hides things. A BankAccount should let callers deposit money, but not set the balance to a million dollars directly. A library should expose a clean API and keep its helper functions private so it can rewrite them later without breaking anyone. Access control is how Swift draws these lines, and the compiler enforces every one of them.

Swift has six levels of access, from most open to most restricted: open, public, package, internal, fileprivate and private. They are defined in terms of two things: the module (a unit of code distributed as a library, an app or a package) and the source file. Before the levels, a quick word on those two ideas.

Modules and source files

A module is everything compiled together as one unit: your app is one module, and Foundation is another. When you import Foundation, you can only use what Foundation exposed to you. A source file is a single .swift file.

On this site every example is one file, main.swift, inside one module. That means you cannot demonstrate the difference between internal and public here (both are visible everywhere in a single module). Those lines are shown as read-only snippets. private and fileprivate can be demonstrated, and so can their compile errors.

The six levels at a glance

Level Visible from Typical use
open any module; classes can be subclassed and members overridden outside frameworks designed for subclassing
public any module; no subclassing or overriding outside a library's public API
package all modules in the same Swift package splitting a big app into several targets
internal anywhere in the same module the default
fileprivate the same source file helpers shared by several types in one file
private the enclosing declaration and its extensions in the same file implementation details

If you write nothing, a declaration is internal. That is a good default for apps: everything is visible inside the app, nothing leaks to other modules.

private: hiding implementation details

Put private on a property or method and only code inside the same type (and its extensions in the same file) can use it.

Swift private keeps the balance consistent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Outsiders can ask canAfford and call deposit, but cannot touch balance. All the rules (no negative deposits) live in one place. Notice private(set): the property can be read by anyone but written only inside the type. This is the single most useful pattern in everyday Swift.

What the compiler says

Swift Touching a private property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error is 'code' is inaccessible due to 'private' protection level. The same message appears for any access level the caller cannot see. Notice also that the memberwise initializer of a struct with a private stored property without a default becomes private, too (calling it from outside gives 'Safe' initializer is inaccessible due to 'private' protection level); add an explicit init so others can create the type. A private(set) property violation has a different message, shown next.

Swift Writing to a private(set) property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Here the message is cannot assign to property: 'value' setter is inaccessible. Reading counter.value is fine; only the assignment is rejected.

fileprivate and private at file scope

fileprivate makes a declaration visible to everything in the same file. At the top level of a file, private behaves the same as fileprivate, because the enclosing scope is the file. Inside a type, the two differ: private is restricted to that type (and same-file extensions), while fileprivate also opens it to other types in the file.

Swift fileprivate shares within one file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Dashboard can read rpm because it is fileprivate, but not temperature. The extension of Engine in the same file can see both. Reach for fileprivate sparingly, for two or three tightly related types in one file; plain private is almost always what you want.

Access control and extensions

An extension can use the access level of the type it extends as its default. You can also give the whole extension a level (private extension) or individual members:

Swift private extension groups helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Splitting a type into a main declaration plus private extension blocks is a common style for keeping a long file tidy. Because the extension is in the same file, the main body can call decorate.

The rule of consistency

A declaration can never be more visible than the types it uses. A public function cannot take an internal type as a parameter: other modules could not name it. The compiler reports this, so you design from the inside out.

Swift A public function using a private type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler complains that the function cannot be declared public because its parameter uses a private type. Make the function private or fileprivate, or make the type visible enough.

public, open and package (read-only)

The next snippets need more than one module, so they are examples to read, not run.

Swift
// In a library module named GeometryKit (read-only example)
public struct Point {
    public var x: Double
    public var y: Double

    // A public struct does NOT get a public memberwise init;
    // you have to write one so other modules can create Points.
    public init(x: Double, y: Double) {
        self.x = x
        self.y = y
    }
}

open class Shape {                 // other modules may subclass this
    public init() {}
    open func area() -> Double { 0 }       // and override this
    public func describe() -> String { "area \(area())" }  // cannot be overridden outside
}

Remember these library rules:

  • The memberwise and default initializers of a public type are only internal. Write a public init.
  • public classes can be subclassed only inside their own module; open allows it everywhere. Prefer public and open things up on purpose, because every open member is a promise you must keep.
  • package (Swift 5.9+) shares code between the targets of one Swift package without exposing it to the world. It is ideal for large apps split into modules.

Another tool in the same family is @testable import, which lets unit tests see internal declarations without making them public. See Testing.

Choosing a level

  1. Start with the narrowest level that works: private.
  2. Widen only when something else needs it: fileprivate, then internal (the default).
  3. For libraries, expose a deliberately small public API.
  4. Use private(set) for properties that others read but should not write.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the default access level when you write no modifier?

    Declarations are internal by default: visible anywhere in their own module.
  2. 2. What does private(set) var count = 0 allow?

    private(set) restricts the setter while the getter keeps the property's normal access level.
  3. 3. What is the difference between public and open for a class?

    open is the only level that lets other modules subclass a class or override its members.
  4. 4. Which level shares code between targets of one Swift package without exposing it publicly?

    package (Swift 5.9+) is visible to all modules in the same package.
  5. 5. Why can't a public function take a parameter of a private type?

    A declaration cannot be more visible than the types in its signature.

Summary

  • Six levels: open, public, package, internal (default), fileprivate, private.
  • Modules and source files define the boundaries.
  • private hides implementation details; private(set) gives read-only access from outside.
  • fileprivate shares inside one file; same-file extensions can use private members.
  • A declaration cannot be more visible than the types it uses.
  • Public types need explicit public init; open is the only level that allows outside subclassing.
  • Start narrow and widen only when needed.

Next: Enumerations