Fix: Understanding Swift Access Modifiers (open, public, internal, fileprivate, private)

Fix: Understanding Swift Access Modifiers (open, public, internal, fileprivate, private)

Written by

in

Quick answer: Swift has five access levels: open and public (usable outside the module), internal (default, module-only), fileprivate (file-only), and private (declaration-only). Use open for classes meant to be subclassed externally, public for framework APIs, internal for app-internal code, fileprivate for file-scoped helpers, and private for implementation details within a single type.

Why this happens

Swift’s access control system replaces Objective-C’s @public, @protected, and @private with five distinct levels that work at module, file, and declaration granularity. Confusion often arises because open and public look similar but differ in subclassing and overriding rules, while fileprivate and private have subtle scope differences that changed between Swift 3 and Swift 4.

The compiler enforces these rules at build time, so mismatched access levels produce errors like 'x' is inaccessible due to 'private' protection level or Class 'B' cannot be subclassed from different module. Understanding the hierarchy prevents these errors and lets you design clean module boundaries.

How to fix it

1. Choose the right level for framework APIs

When building a framework, mark the public interface public by default. Only use open on classes and overridable members that you explicitly want consumers to subclass or override outside your module.

// MyFramework/PublicAPI.swift
public struct Configuration { }

open class BaseViewController: UIViewController { }

public class FinalService { }
// FinalService cannot be subclassed outside MyFramework

2. Use internal (default) for app-internal code

Within an app target, internal is the default and requires no keyword. It allows free access across all files in the same target while keeping symbols hidden from other modules.

// App/Networking/ApiClient.swift
struct ApiClient { } // internal by default

// App/Features/Login/ViewModel.swift
let client = ApiClient() // OK — same module

3. Restrict helpers to a single file with fileprivate

When a property or helper is used in multiple types within the same file but shouldn’t leak outside, mark it fileprivate.

// Models/User.swift
fileprivate let dateFormatter: ISO8601DateFormatter = {
    let f = ISO8601DateFormatter()
    f.formatOptions = [.withInternetDateTime]
    return f
}()

struct User {
    let createdAt: Date
    var createdAtString: String { dateFormatter.string(from: createdAt) }
}

struct UserProfile {
    let user: User
    var displayDate: String { dateFormatter.string(from: user.createdAt) }
}

4. Hide implementation details with private

Use private for properties and methods that only the enclosing type (and its extensions in the same file) should see. This is the strictest level and the best default for implementation details.

class Cache {
    private var storage: [String: Data] = [:]
    private let queue = DispatchQueue(label: "cache.queue")

    func object(forKey key: String) -> Data? {
        queue.sync { storage[key] }
    }

    func setObject(_ data: Data, forKey key: String) {
        queue.sync { storage[key] = data }
    }
}

// Extension in same file can access private members
extension Cache {
    func removeAll() { queue.sync { storage.removeAll() } }
}

5. Understand the open vs. public subclassing rule

open classes and members can be subclassed and overridden outside the defining module. public classes and members can be used but not subclassed or overridden outside the module. Inside the module, both behave identically.

// Framework target
open class Animal { open func speak() { } }
public class Vehicle { public func start() { } }

// App target importing Framework
class Dog: Animal { override func speak() { } } // OK
// class Car: Vehicle { override func start() { } } // Error: Vehicle not open

How to prevent it

  • Default to private for all new properties and methods; widen only when the compiler forces you to.
  • Mark framework-facing types public and only promote to open when you design for external subclassing.
  • Keep fileprivate for file-scoped shared state (formatters, caches, constants) instead of polluting the module namespace.
  • Remember that internal is implicit — omit the keyword to reduce noise.
  • Test framework consumers in a separate module target to catch access-level mistakes early.

FAQ

Can I make a stored property open?

No. open applies only to classes, class members (methods, properties, subscripts), and initializers. Structs, enums, and protocols cannot be open.

Why does my extension in another file lose access to private members?

private members are visible only inside the original declaration and extensions in the same file. Move the extension to the same file or change the member to fileprivate if cross-file access within the module is needed.

What is the default access level if I write nothing?

internal. Entities declared without an explicit modifier are accessible anywhere within the same module (app or framework target) but not outside it.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.