Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Access Control

Swift Access Control

Access control determines "who can see, use, and inherit a piece of code".

Swift has six access levels, from the strictest to the most open: private, fileprivate, internal, package, public, and open.

Many older resources only go as far as public and describe private as "only accessible inside a class"—both of these are inaccurate.

This article explains all six levels one by one and covers easily overlooked usages such as open, package, and private(set).


Overview of the six access levels

First, take a look at the overall comparison table; each section below expands on them one by one.

Level Visibility scope Cross-module accessible Cross-module inheritance or override allowed
private Scope where declared + extensions in the same file No No
fileprivate Entire source file where declared No No
internal Module where declared (default level) No No
package All modules within the same package Yes within the package No, open is still required
public Any module Is No
open Any module Is Is

There are two common pitfalls here.

First, public is not the highest level—open is—and open can only be used on classes and class members.

Second, package is broader than internal but narrower than public; it targets "multiple modules within the same Swift Package".


private: declaring scope plus extensions in the same file

private is the strictest level, but it does not mean "only accessible inside a class".

The accurate statement is: private members are visible inthe scope where they are declaredandand extensions in the same file.

Example

import Foundation

struct

RunoobUser

{

   

private

var token

:

String

=

"RUNOOB-SECRET"

    fileprivate var site

:

String

=

"www.runoob.com"

   

private

(

set

)

var visitCount

:

Int

=

0

    mutating func visit

(

)

{

        visitCount

=

1

 

// Can be written inside the type

   

}

}

extension RunoobUser

{

   

// Extensions in the same file can access private members

    func maskedToken

(

)

String

{

        String

(

token.

prefix

(

3

)

)

"****"

   

}

}

var user

=

RunoobUser

(

)

user.

visit

(

)

user.

visit

(

)

print

(

user.

visitCount

)

         

// Readable from outside

print

(

user.

maskedToken

(

)

)

print

(

user.

site

)

               

// fileprivate: readable and writable in the same file



2

RUN****

www.runoob.com

As you can see, maskedToken() in the extension directly reads token, and compilation has no problem at all.

Common misconception:"private is only accessible inside a class" is wrong. Since Swift 4,private the scope of private has been expanded to "declaring scope + extensions in the same file". If you split the type definition and its extension into two files, the extension can no longer access private members; in that case you need to use fileprivate。


fileprivate: visible throughout the source file

fileprivate widens visibility to the entire .swift file, so other types in the same file can also access it.

Example

import Foundation

struct

RunoobUser

{

    fileprivate var site

=

"www.runoob.com"

}

// Other types in the same source file can access fileprivate members

struct

RunoobLogger

{

    func

log

(

_ user

:

RunoobUser

)

String

{

       

"Site: (user.site)"

   

}

}

print

(

RunoobLogger

(

)

.

log

(

RunoobUser

(

)

)

)



站点:www.runoob.com

If site above were changed to private, RunoobLogger could not access it, because the two types are two separate scopes.

In real development, fileprivate is typically used when "a group of types in the same file need to share an implementation detail".


internal: the default level within a module

When no modifier is written, a member is internal, visible throughout the module.

A module is a compilation unit: an App target, a framework, or a target within a Swift Package all count as modules.

So "visible within the same module" is usually equivalent to "visible within the same target"; using it across targets requires promoting it to public.

The single-file examples in the previous sections can only verify behavior within internal; cross-module rules require a real Swift Package to observe.


package: multiple modules within the same package

A Swift Package often has multiple targets, each an independent module; by default they cannot see each other's internal members.

If you don't want to expose an internal API as public but still want to share it across multiple modules in the same package, use package.

The package below has two targets: the library target RunoobKit and the executable target RunoobApp.



Sources/

├── RunoobKit/

│   └── RunoobKit.swift      // 库模块,对外暴露 package 级别函数

└── RunoobApp/

    └── main.swift           // 可执行模块,同包内可访问 package 成员

Example

// File path: Sources/RunoobKit/RunoobKit.swift

import Foundation

// package: visible to other modules in the same package, not visible outside the package

package func runoobInternalName

(

)

String

{

   

"RUNOOB"

}

Example

// File path: Sources/RunoobApp/main.swift

import Foundation

import RunoobKit

// Another module in the same package can call package members normally

print

(

runoobInternalName

(

)

)



RUNOOB

If you use this package as a dependency and, fromanother package, call runoobInternalName(), compilation will fail outright.



error: cannot find 'runoobInternalName' in scope

In other words, the boundary of package is the "package", while the boundary of internal is the "module".

It should be emphasized that what package relaxes is onlyvisibility, not inheritance permission.

A package class still cannot be inherited in another module within the package; it must still be declared open.

Implementation detail:The compiler needs a -package-name flag to recognize package boundaries. When building with SwiftPM, this flag is passed automatically and needs no manual configuration; if you compile a multi-module project directly with swiftc , you must add it yourself.


public: visible across modules, but cannot be inherited or overridden

public makes members accessible from any module and is the common level for a framework's public API.

But it has a key limitation: code outside the module canUse, but cannotinheritancethis class, nor can itrewrittenits members.



error: cannot inherit from non-open class 'RunoobHelper' outside of its defining module

This design is intentional: framework authors use public to mean "you can call it, but I don't want you to change my behavior".


open: inheritable and overridable across modules

Only open allows inheriting classes, overriding methods, or overriding properties from outside the module.

open can only modify the class itself and members that can be overridden by subclasses; it cannot be used with structs, enums, or protocols.

The package below demonstrates the differences among the three levels in a cross-module scenario.

Example

// File path: Sources/RunoobKit/RunoobKit.swift

import Foundation

// open: can be inherited and overridden outside the module

open

class

RunoobBase

{

   

public

init

(

)

{

}

    open func describe

(

)

String

{

"RunoobBase"

}

}

// public: visible outside the module, but cannot be inherited or overridden

public

class

RunoobHelper

{

   

public

init

(

)

{

}

   

public

func name

(

)

String

{

"www.runoob.com"

}

}

public

struct

RunoobPublicStruct

{

   

public

let site

:

String

   

public

init

(

site

:

String

)

{

self.

site

=

site

}

}

package func runoobInternalName

(

)

String

{

"RUNOOB"

}

Example

// File path: Sources/RunoobApp/main.swift

import Foundation

import RunoobKit

// open classes can be inherited across modules, and open methods can be overridden

final

class

RunoobChild

:

RunoobBase

{

    override func describe

(

)

String

{

"RunoobChild"

}

}

print

(

RunoobChild

(

)

.

describe

(

)

)

print

(

RunoobHelper

(

)

.

name

(

)

)

print

(

RunoobPublicStruct

(

site

:

"www.runoob.com"

)

.

site

)

print

(

runoobInternalName

(

)

)



RunoobChild

www.runoob.com

www.runoob.com

RUNOOB

Change RunoobBase's open to public, and the inheritance code above will produce the error mentioned earlier.

Another detail: if a member of an open class is marked public, it still cannot be overridden outside the module; only members marked open can be.


private(set): read-only externally, writable internally

Access levels can control reading and writing separately, written as private(set) or, more generally, AccessLevel(set).

It means the getter keeps its original level while the setter is lowered to the level in the parentheses.

Example

import Foundation

struct

RunoobUser

{

   

private

(

set

)

var visitCount

:

Int

=

0

    mutating func visit

(

)

{

visitCount

=

1

}

}

var user

=

RunoobUser

(

)

user.

visit

(

)

print

(

user.

visitCount

)

 

// Readable from outside



1

Reading is fine, but as soon as outside code tries to assign, the compiler stops it.

Example

import Foundation

struct

RunoobUser

{

   

private

(

set

)

var visitCount

:

Int

=

0

    mutating func visit

(

)

{

visitCount

=

1

}

}

var user

=

RunoobUser

(

)

user.

visit

(

)

user.

visitCount

=

100

   

// Not writable from outside



error: cannot assign to property: 'visitCount' setter is inaccessible

This style suits properties like counters and state that can only be modified internally and read externally, and is more concise than writing a computed property.

Similarly, internal(set) means "read-only outside the module, writable inside", and fileprivate(set) means "read-only outside the file, writable inside".


Why doesn't Swift have protected

Developers coming from C++ or Java often ask: why doesn't Swift have protected?

The reason lies in the different organizational dimensions of access control. C++'s protected is based on the "class inheritance hierarchy", while Swift's access control is based on "modules" and "files".

Swift makes heavy use of value types and protocol extensions, which have no inheritance relationships, so protected makes no sense in this structure.

In addition, protected creates strong coupling between subclasses and superclasses, while Swift encourages using protocol abstraction, composition, and module boundaries to manage dependencies.

When you need a member "visible only to the internal implementation", Swift's approach is to use internal or fileprivate to control scope rather than relying on inheritance.


Constructor visibility

Initializers follow the same access rules, but there is one easily overlooked point:Implicitly generated initializers are not automatically promoted to public。

For a public struct, if you don't write an init, its memberwise initializer remains internal and cannot be used across modules.

Example

// File path: Sources/RunoobKit/RunoobKit.swift

public

struct

RunoobPublicStruct

{

   

public

let site

:

String  

// No explicit init

}



error: 'RunoobPublicStruct' initializer is inaccessible due to 'internal' protection level

The solution is to explicitly write a public init, as done in the earlier examples.

Conversely, making an initializer private can force outside code to create instances only through specific entry points, a common pattern for singletons.

Example

import Foundation

@MainActor

final

class

RunoobConfig

{

   

// Singleton: initializer set to private, outside code can only obtain the instance via shared

   

static

let shared

=

RunoobConfig

(

)

   

private

init

(

)

{

}

    var site

=

"www.runoob.com"

}

func runoobDemo

(

)

async

{

    print

(

await RunoobConfig.

shared

.

site

)

}

await runoobDemo

(

)



www.runoob.com

At this point, writing RunoobConfig() from outside produces an error immediately.



error: 'RunoobConfig' initializer is inaccessible due to 'private' protection level


Visibility of extensions

An extension itself can carry an access-level modifier, which sets a default level for all members in the extension.

For example, members in a public extension are public by default, so you don't need to write it for each one.

An individual member in an extension can still override this default, but cannot raise the level beyond the visibility of the extended type itself.

Example

import Foundation

struct

RunoobHelper

{

}

extension RunoobHelper

{

   

private

func secret

(

)

String

{

"RUNOOB"

}

}

extension RunoobHelper

{

    func reveal

(

)

String

{

secret

(

)

}

 

// Another extension in the same file

}

print

(

RunoobHelper

(

)

.

reveal

(

)

)



RUNOOB

This example again shows that private's scope is "declaring scope + extensions in the same file", not "only inside the braces where it is declared".

If you split these two extensions into two files, reveal() can no longer access secret().


Common questions

Can a type's member be more open than the type itself

No. A member's maximum visibility is limited by the visibility of its containing type.

For an internal struct, even if you write a member as public, the actual effect is still internal.

How to choose between open and public

Use open only when you truly want users to be able to inherit or override.

Choosing public by default is safer because it preserves the freedom to change the internal implementation later.

How to distinguish the boundaries of package and internal

internal's boundary is a single module, that is, one target.

package's boundary is the entire package, covering all targets in the package, but completely invisible outside the package.

Does private(set) change the getter's level

No. It only lowers the setter's level; the getter keeps its original access level.

Therefore, outside code can still read the property, just not assign to it.

Why can't my public class be inherited in another module

Because public only guarantees visibility, not inheritability.

When cross-module inheritance is needed, declare the class as open and ensure the members to be overridden are also open.