Swift 3 Access Control

Ryuichi Sai
2 min readSep 2, 2016

--

Swift 3 brought significant changes to the access control. Instead of public, internal, and private that we are used to, now in Swift 3, we have open, public, internal, fileprivate, and private. In addition, the definition of private and public are big changes with renaming the formerly known private to fileprivate and public to open. We’ll take a look at each of them.

open & public

New access modifier open is introduced, and it serves as what public did in earlier Swift versions: for classes, it allows other modules to use the class and inherit the class; for members, it allows others modules to use the member and override it.

public in Swift 3 is stricter, it only allows other modules to use the public classes and the public members. Public classes can no longer be subclassed, nor public members can be overridden.

To show this in a table:

internal

internal keeps the same, and it’s still the default access level. Internal classes and members can be accessed anywhere within the same module they are defined.

fileprivate and private

Classes and members can only be accessed within a limited scope where they are defined, private in Swift 3 means the lexical scope where they are defined, and fileprivate means the source file where they are defined.

Basically fileprivate is accessible within the current file, whereas, private is accessible within the current declaration (in other words, in the same curly braces).

Conclusions and other considerations

There are five level of access controls in Swift 3, namely open, public, internal, fileprivate, and private, from most liberal to the most strict.

For testing purposes, @testable import is available to subclass open, public, and internal classes, as well as override open, public, and internal members.

References

--

--