skip to content

Visibility and Interoperability

Access levels decide what a module, file or type exposes, and bridging connects Swift to Objective-C, C and C++. Interviewers ask open versus public and how nullability maps.

on this pageshow

explore

questions

12

In Swift, what access level does a declaration get when you write no modifier, and how do `private` and `fileprivate` differ, including in extensions?

level: juniorimportance: must knowfreq 75%

answer

  1. module-wide unless you say otherwise
  2. scope versus file
  3. same-file extensions share one scope
  4. subclasses are not extensions

basics

~20 s

With no modifier a Swift declaration is internal: usable in every file of its module, invisible outside it. private limits use to the enclosing declaration and its same-file extensions; fileprivate opens it to the whole source file.

solid answer

~40 s

The default is `internal`, so in a single-target app everything is already visible app-wide and nothing leaks outside the module. `private` is scoped to the enclosing declaration, and since Swift 4 a type and all of its extensions **in the same file** count as one scope: a private member of the type is usable in those extensions, and a private member declared in one extension is usable in the type and its other same-file extensions. Nothing private crosses into another file, and it does not reach a subclass or a free function, even one in the same file. `fileprivate` makes a declaration visible to any code in its source file, which is what you need when a helper function, a sibling type or a subclass written beside the type must touch the member.

code

swift · 22 lines
swift
// ThumbnailCache.swift, one source file of the Core module
struct ThumbnailCache {
    private var entries: [String: Int] = [:]   // this type and its extensions in this file
    fileprivate var hits = 0                    // any code in this file

    mutating func store(_ key: String, size: Int) {
        entries[key] = size
        trim()                                  // private member declared in an extension
    }
}

extension ThumbnailCache {
    private mutating func trim() {
        if entries.count > 100 { entries.removeAll() }
    }
    var count: Int { entries.count }            // no modifier: internal, the whole module
}

func debugSummary(_ cache: ThumbnailCache) -> String {
    // A free function in the same file sees `hits` (fileprivate), not `entries` (private).
    "hits: \(cache.hits), entries: \(cache.count)"
}

go deeper

for a junior

Recall that no modifier means internal, then state private as the declaration plus its same-file extensions and fileprivate as the whole file.

for a middle

Explain the single access scope a type shares with its same-file extensions, and name what it excludes: other files, subclasses and free functions.

for a senior

Show the judgment: default to private, widen to fileprivate only for a named same-file collaborator, and treat a test that needs private state as a missing seam.

for a principal

Frame the rule a team adopts for narrowing access by default, and how reviews catch fileprivate used out of habit rather than need.

## The six levels and the default Swift's access control is built on three units: the **source file**, the **module** (one build target such as an app, a framework or a test bundle) and the **package** (a group of modules built together). It has six access levels, from widest to narrowest: | Level | Who can use the declaration | |---|---| | `open` | any module that imports it; classes and class members can also be subclassed or overridden there | | `public` | any module that imports it; subclassing and overriding stay inside the defining module | | `package` | any module compiled with the same package name | | `internal` | any source file of the defining module | | `fileprivate` | the defining source file | | `private` | the enclosing declaration, plus extensions of that type in the same file | When you write no modifier, a declaration is **`internal`**. In a single-target app that already means "the whole app", which is why many apps rarely write a modifier except to hide details. A few contexts shift the default: - members of a `private` or `fileprivate` type default to that type's level; - members of a `public` type default to `internal`, not `public`; - enum cases always have their enum's level and cannot be given another; - a protocol's requirements always have the protocol's level. ## `private`: one declaration and its same-file extensions `private` restricts a declaration to the **enclosing declaration**. Since Swift 4 (proposal SE-0169), a type and every extension of it **in the same source file** form a single access scope. That has concrete consequences: - a private stored property of the type is readable and writable in its same-file extensions; - a private method declared in an extension can be called from the type body and from its other same-file extensions; - an extension of the same type in **another file** of the module cannot see it: the compiler reports `'entries' is inaccessible due to 'private' protection level`; - a **subclass** gets no private access, even when it is declared in the same file, because the rule covers extensions of the type itself, not types derived from it; - a free function or a different type in the same file cannot see the private member either. A `private` declaration at the top level of a file has no enclosing type, so its scope is the file: other declarations in that file can use it, other files cannot. ## `fileprivate`: the whole source file `fileprivate` makes a declaration visible to **every declaration in the same source file**: free functions, other types, subclasses and extensions alike. It is the right tool when a collaborator that is neither the type nor its extension must reach a member: a debug helper, a small sibling type that builds the value, or a subclass kept beside its superclass. The attached example is one file of a Core framework: `ThumbnailCache` keeps `entries` private and calls a private `trim()` declared in its own extension, while a free function in the same file can read the `fileprivate` counter `hits` but not `entries`. ## Common mistakes - Expecting a superclass's `private` member to be usable from a subclass, as a protected level would allow; Swift has no protected level, so the member needs `fileprivate` (subclass in the same file) or `internal` (same module). - Splitting a type's extensions into separate files for tidiness, then finding they can no longer touch the type's private storage. - Assuming a modifier on an extension, such as `fileprivate extension`, widens access to members declared elsewhere; it only sets the default for the members that extension declares. ## Choosing a level 1. Start with the narrowest level that compiles: `private` for storage and helpers only the type itself uses. 2. Widen to `fileprivate` only when a same-file collaborator outside the type and its extensions needs the member. 3. Leave the rest `internal`, and widen to `package`, `public` or `open` only when another module must see it. Two signals in code review: `fileprivate` sprinkled on members that only same-file extensions use, a habit left over from before Swift 4 when `private` did not reach extensions; and private state a test cannot reach, which usually asks for an internal seam rather than a wider modifier, since even `@testable import` never exposes `private` or `fileprivate`.

  • Can a Swift extension in another file add a `private` member and use it from the type's original declaration?
    No. The shared scope only covers the type and its extensions in the **same** file. A `private` member declared in an extension in another file is visible to that extension and to other extensions of the type in that file, but the original declaration in its own file cannot see it, and the extension cannot see the original declaration's private members either.
  • Does putting a modifier on the extension itself, such as `private extension ThumbnailCache`, change who can see the type's existing private members?
    No. A modifier on an extension only sets the default access level of the members that extension declares; each member may still override it. It grants nothing extra. An extension that adds a protocol conformance cannot carry an access modifier at all; the requirement implementations take their default from the protocol instead.

  • Swift declarations without a modifier are public to every importing module
  • private members are visible to every extension of the type in the module
  • A subclass in the same file can call its superclass's private methods
  • fileprivate and private are the same thing since Swift 4
  • A free function in the same file can read a type's private properties
open as a page

In a mixed Swift and Objective-C app, why can't an Objective-C file call a new Swift method, and what makes it visible?

level: middleimportance: must knowfreq 62%

basics

~20 s

Objective-C sees Swift only through the compiler-generated ModuleName-Swift.h header, which prints only declarations exposed with @objc. Since Swift 4, sitting in an NSObject subclass no longer exposes a method by itself, so a new method needs @objc and Objective-C-representable types.

open as a page

When Swift imports an Objective-C header, how do nullability annotations, lightweight generics and NS_ENUM declarations decide the Swift types you get?

level: middleimportance: must knowfreq 58%

basics

~20 s

Unannotated Objective-C pointers import as implicitly unwrapped optionals, nullable as optionals, nonnull as plain types; NSArray<NSString *> becomes [String] while a bare NSArray becomes [Any]; NS_ENUM becomes a non-frozen Swift enum and NS_OPTIONS an OptionSet struct.

open as a page

In Swift, what is the difference between `open` and `public` on a class and its methods for code in another module?

level: middleimportance: must knowfreq 70%

basics

~20 s

Both make a class and its members usable from other modules. Only open also lets another module subclass the class or override the member; a public class can be subclassed, and its public methods overridden, only inside its defining module.

open as a page

In Swift, how do `private(set)` and `internal(set)` restrict a property's setter, and what can code outside that scope still do with it?

level: middleimportance: must knowfreq 65%

basics

~20 s

A setter modifier gives a property's setter a lower access level than its getter. Outside that scope code can read the property, but cannot assign it, pass it inout or call a mutating member on it.

open as a page

In Swift, what does `@testable import` let a test target see, and why must the imported module be built with `-enable-testing`?

level: middleimportance: should knowfreq 55%

basics

~20 s

A testable import treats the module's internal declarations as public and its internal or public classes and members as open, so tests can call internals and subclass. It fails with an error unless the module was compiled with -enable-testing.

open as a page

A Swift NSObject subclass's property is observed with KVO, yet assignments made from Swift never notify; why does it need @objc dynamic?

level: seniorimportance: should knowfreq 45%

basics

~20 s

KVO notifies by intercepting the setter through the Objective-C runtime. @objc only adds an Objective-C entry point; Swift callers still reach the setter through Swift's own dispatch and bypass the interception. dynamic forces every access through Objective-C messaging, so the observer fires.

open as a page

A Swift call into a C image-decoding library returns Unmanaged<CFData>?; what does that tell you, and how do you choose takeRetainedValue or takeUnretainedValue?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Unmanaged means Swift could not tell whether the C function returns an owned (+1) or borrowed (+0) Core Foundation object. Use takeRetainedValue for Create or Copy functions, which hand you ownership, and takeUnretainedValue for Get functions, which do not.

open as a page

A Swift Core framework declares `public struct Session`, yet the Feature module cannot create a Session or read its properties; why, and what fixes it?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Members of a public type default to internal, and its implicit default and memberwise initializers are never public. Mark each member Feature needs as public and write an explicit public init; any type those members expose must be public too.

open as a page

For an app with a decade of Objective-C screens, a C image decoder and Objective-C++ wrappers around a C++ geometry library, how would you plan the Swift migration of its interop boundaries?

level: principalimportance: should knowfreq 30%

basics

~20 s

Annotate the Objective-C and C headers first, write new leaf code as @objc Swift, port classes Objective-C still subclasses with @objc @implementation (Swift 6.1), and replace Objective-C++ wrappers with C++ interoperability only behind one Swift module that keeps the mode contained.

open as a page

As the lead of a Swift codebase split into Core and Feature modules in one package plus an app, what do you make `public` versus `package`, and what import access policy do you set?

level: principalimportance: should knowfreq 30%

basics

~20 s

Make public only what modules outside the package must use, give cross-module plumbing package access, and leave the rest internal. Then decide whether imports stay implicitly public or become explicit, with InternalImportsByDefault and public import for real API dependencies.

open as a page

In Swift, what changes when a target enables C++ interoperability mode to call a C++ geometry library, and what must modules importing it do?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

With -cxx-interoperability-mode=default, Swift imports C++ headers directly: copyable C++ classes become Swift value types, std::string and std::vector become usable, and annotated reference-counted classes become ARC-managed references. Modules that see those C++ types through a public import must enable the mode too.

open as a page