ThisCalculator

Everyday

Swift Access Control: What It Is & How to Use It

Updated · Standard formula, shown below

Swift access control lets you restrict how code in one file, module, or scope can be used by other code. By placing the keywords open, public, internal, fileprivate, or private before a declaration, you decide exactly who can see and modify that declaration. This article explains each level, how to choose between them, and common pitfalls, with concrete examples you can try in Xcode.

Why Access Control Exists

Access control is a core part of Swift’s design, not an optional extra. It serves three main purposes:

  • Encapsulation – hide implementation details so callers only interact with a clean public interface.
  • Safety – prevent accidental modification of internal state that could break invariants (e.g., a bank account balance).
  • API stability – once you ship a framework, you can change private internals freely without breaking users, but changing public signatures is a breaking change.

Without access control, every property and method would be visible everywhere, making it nearly impossible to refactor code or guarantee that data stays consistent.

The Five Access Levels

Swift provides five levels, from most restrictive to least restrictive:

  1. private – accessible only within the enclosing declaration (e.g., inside a class or extension).
  2. fileprivate – accessible anywhere in the same source file.
  3. internal (default) – accessible within the same module (app or framework).
  4. public – accessible from any module, but you cannot override or subclass from outside the defining module.
  5. open – same as public, plus you can subclass and override from other modules.

The default is internal, so if you don’t write a modifier, your code is visible throughout your app. For a framework, you must explicitly mark the API you want to expose as public or open.

How to Choose the Right Level

A simple rule: start with private and loosen only when needed. Concretely:

  • Use private for helper methods, stored properties that should never be touched directly, and internal state.
  • Use fileprivate when two types in the same file need shared access to something that should stay hidden from the rest of the module.
  • Use internal for anything that other parts of your app need but that should not be exposed to the outside world.
  • Use public for framework functions and properties that consumers need, but that you don’t want subclassed.
  • Use open only when you explicitly want to allow subclassing or overriding from outside the module.

For example, a settings manager in an app might have a private var theme and an internal func applyTheme(). If you later build a framework, you’d mark the public API as public but keep the theme storage private.

Common Mistakes and Pitfalls

Even experienced developers trip over a few subtle points:

  • Private and extensions – In Swift 4+, private members are accessible in extensions of the same type in the same file. This is handy but can be confusing if you expect true privacy.
  • Protocol conformance – If a type conforms to a protocol, the conformance must be at least as accessible as the protocol itself. A private type cannot publicly conform to a public protocol.
  • Getters and setters – You can set a property as private(set) to allow reading but not writing from outside. This is a common pattern for read-only public data.
  • Default parameters – Default values in a function must be at least as accessible as the function itself. A public function cannot have a private default value.
  • Type inference – A variable’s access level cannot be more restrictive than its type. If you have a private struct, you cannot have a public property of that type.

Access Control in Practice

Here’s a small example showing the levels in action:

public class BankAccount {
    private var balance: Double = 0.0
    
    public func deposit(_ amount: Double) {
        balance += amount
    }
    
    public func withdraw(_ amount: Double) -> Bool {
        guard amount <= balance else { return false }
        balance -= amount
        return true
    }
    
    public var currentBalance: Double {
        return balance
    }
}

Here, balance is private, so no outside code can read or modify it directly. The public methods provide a controlled interface. If you tried to set balance from outside, you’d get a compile error.

Comparison with Other Languages

If you come from Java or C#, the levels map roughly as follows:

  • private – same as Java’s private.
  • fileprivate – similar to Java’s package-private (but file-based, not directory-based).
  • internal – similar to Java’s package-private (but module-based).
  • public – similar to Java’s public, but without subclassing.
  • open – closest to Java’s public with inheritance.

Unlike C++, Swift does not have friend classes or global friends. The fileprivate level is the closest equivalent for sharing within a file.

Frequently Asked Questions

What is the default access level in Swift?

The default is internal. If you write var x = 5 at the top level of a file, it is visible anywhere in the same module (your app or framework), but not to other modules.

Can I make a getter public but setter private?

Yes, use private(set) on the property. For example, public private(set) var count = 0 lets anyone read count but only the type itself can change it.

Why can’t I override a public method in a subclass from another module?

Because public only allows access, not inheritance. To allow subclassing and overriding, you must use open. This distinction exists so framework authors can prevent subclassing unless they explicitly allow it.

Does access control affect performance?

No. Access control is enforced at compile time and has zero runtime overhead. It’s purely a compile-time check to catch mistakes early.

Can I change access level in an extension?

Yes, you can add new members in an extension with a different access level, but you cannot change the access level of existing members. Also, remember that private members are visible in extensions of the same type in the same file.

What happens if I make a whole type private?

Then the type is only usable within the enclosing scope (e.g., inside a class). This is useful for helper structs that should never escape. However, you cannot have a public property of that private type.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.