Swift Access Specifiers

Payal Kandlur
2 min readAug 23, 2021

--

The types

  1. private — The most strict access level, properties or methods declared as private are accessible only within the defining type(that is, the class or the structure) or within the defining source file if the classes, structures, enumerations or protocols are declared private. Entities cannot be accessed outside the defining type or file.
  2. public — Declaring entities as public makes them accessible outside the defining module or within the same module. If you have a library integrated into a project as a Swift Package, entities that should be available to the project out of the library must be marked as public, else they won’t be accessible.
  3. file-private — This is a less strict access level, entities marked as file-private are visible and accessible from any other entity within the same source file and not outside of it.
  4. internalThe default access level in Swift! By default, all entities are internal unless specified. These are the entities that can be accessed through the defining module but not outside that particular module or any other module.
  5. open — Similar to public, but it provides an additional feature — Classes and methods marked as open can be subclassed and overridden respectively out of their defining module.

File-private vs Private

File-private restricts the use of the entity within its own source file. Private restricts the use of the entity within the enclosing declaration or the extension of that declaration in the same file! File-private can be accessed by the subclass in the same file whereas private cannot.

Open vs Public

An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.

A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.

That’s all!😊 Do comment your thoughts below.

--

--

No responses yet