TExcelTAD
Home › Swift › Swift Access Control

Swift Access Control

Access control decides which parts of your code can see and use a type, property or method. It lets you hide implementation details behind a small, clear interface, so other code cannot put your objects into an invalid state — and so you can change the internals later without breaking anyone.

The access levels

Swift's access levels are based on modules (an app target, a framework or a Swift package) and source files.

Level Visible from Typical use
open Any module; classes can be subclassed and overridden outside the module Framework classes meant for subclassing
public Any module (but no subclassing/overriding outside) A library's API
package Any module in the same Swift package Shared helpers between a package's modules
internal (default) Anywhere in the same module Most app code
fileprivate Only the same source file Helpers shared by types in one file
private Only the enclosing declaration (and its extensions in the same file) Implementation details

If you write nothing, a declaration is internal. In a single app you mostly use the default, private and fileprivate.

Hiding state with private

The classic use: keep a stored property private so it can only change through methods that enforce your rules.

swift · try it yourself
struct BankAccount {
    let owner: String
    private var balance = 0      // nobody outside can touch this directly

    init(owner: String) { self.owner = owner }

    mutating func deposit(_ amount: Int) {
        guard amount > 0 else { return }
        balance += amount
    }

    mutating func withdraw(_ amount: Int) -> Bool {
        guard amount > 0, amount <= balance else { return false }
        balance -= amount
        return true
    }

    func statement() -> String { "\(owner): \(balance)" }
}

var acc = BankAccount(owner: "Quang")
acc.deposit(100)
print(acc.withdraw(30))
print(acc.withdraw(500))
print(acc.statement())
true
false
Quang: 70

Because balance is private, the balance can never become negative: there is no way around withdraw. Trying to access it from outside is a compile error:

swift · try it yourself
struct Vault {
    private var secret = "1234"
}

let v = Vault()
print(v.secret)
error: emit-module command failed with exit code 1 (use -v to see invocation)
<source>:6:9: error: 'secret' is inaccessible due to 'private' protection level
1 | struct Vault {
2 |     private var secret = "1234"
  |                 `- note: 'secret' declared here
3 | }
4 |
5 | let v = Vault()
6 | print(v.secret)
  |         `- error: 'secret' is inaccessible due to 'private' protection level

Read-only from outside: private(set)

Often you want others to read a property but only your type to change it. Give the setter a lower access level with private(set):

swift · try it yourself
struct StepCounter {
    private(set) var steps = 0

    mutating func walk(_ n: Int) {
        steps += n
    }
}

var counter = StepCounter()
counter.walk(1200)
counter.walk(800)
print("Steps today:", counter.steps)   // reading is fine
// counter.steps = 0  ← error: setter is inaccessible
Steps today: 2000

private vs fileprivate

private members are visible inside the type and in its extensions in the same file. fileprivate widens that to every declaration in the file — useful when two small types in one file must cooperate.

swift · try it yourself
struct Engine {
    fileprivate var temperature = 90     // visible to anything in this file
    private var serialNumber = "EN-77"   // visible only inside Engine (+ its extensions here)
}

extension Engine {
    func label() -> String { "Engine \(serialNumber)" }   // allowed: same type, same file
}

struct Mechanic {
    func check(_ engine: Engine) -> String {
        engine.temperature > 100 ? "Overheating" : "OK at \(engine.temperature)°"
    }
}

let engine = Engine()
print(engine.label())
print(Mechanic().check(engine))
Engine EN-77
OK at 90°

If Mechanic tried to read engine.serialNumber, the compiler would reject it.

Note: All playgrounds on this site are a single file in a single module, so you can't observe the difference between internal, public and open here. Those levels matter when you split code into frameworks or Swift packages.

Rules that keep access consistent

Swift enforces a simple guiding principle: an entity cannot be more visible than the types it uses.

  • A public function cannot take a private type as a parameter or return it.
  • A type's members default to internal even if the type is public — you must mark API members public explicitly.
  • A private type's members are effectively private too.
swift
public struct Profile {
    public let username: String        // part of the public API
    var lastLogin = 0                  // internal: hidden from other modules

    public init(username: String) {    // public types need an explicit public init
        self.username = username
    }
}

Tip: Start everything as private and widen the access level only when another piece of code actually needs it. It is easy to make something more visible later, but hard to take visibility away once others depend on it.

Test yourself

What is the default access level when you write nothing?

  1. private
  2. public
  3. internal
  4. fileprivate

What does private(set) var steps = 0 mean?

  1. Nobody can read steps
  2. Anyone can read steps, but only the type itself can change it
  3. steps is a constant
  4. steps is visible only in this file

Which level allows subclassing a class from another module?

  1. public
  2. open
  3. internal
  4. package